一、promise的原生实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
/*
*Promise实现思路
* 1.构造函数
* 2.回调函数的参数 resolve reject
* 3.链式调用.then .catch
*/
function PromiseM(cb){
//初始状态
this.status = "pending";
this.msg = "";
cb((data)=>{
this.status = "resolve";
this.msg = data;
},()=>{
this.status = "reject";
})
return this;
}
//链式调用.then
PromiseM.prototype.then = function(){
var cb = arguments;
//轮询实现异步
timer = setInterval(()=>{
if(this.status == "resolve"){
//成功状态的回调
cb[0](this.msg);
clearInterval(timer);
}else if(this.status == "reject"){
//失败状态的回调
cb[1](this.msg);
clearInterval(timer);
}
},3000)
}
new PromiseM(function (resolve,reject){
setTimeout(function (){
console.log(1111);
resolve('11111');/*reject也就是失败时对应的函数,由于这个例子比较简单*/
},1000)
}).then(function (data){
console.log("接收的值为"+data);
})
</script>
</body>
</html>
二、把回调函数写到数组里面,方便后续的all与race
function PromiseM(executor) { //executor执行器
let self = this;
self.status = 'pending'; //等待态
self.value = undefined; // 表示当前成功的值
self.reason = undefined; // 表示是失败的值
function resolve(value) { // 成功的方法
if (self.status === 'pending') {
self.status = 'resolved';
self.value = va