标签:需要 code === fail 方法参数 cat 表示 stat function
<script>
// 构造函数
function MyPromise(callback) {
// 定义当前状态
this.status = ‘pending‘;
// 定义成功时候的回调函数队列
this.successArr = [];
// 定义失败时候的回调函数队列
this.failArr = [];
// 实现成功时候执行的方法 resolve方法
let resolve = value => {
// 改变状态
this.status = ‘resolved‘;
// 依次执行成功队列的方法
this.successArr.forEach(fn => value = fn(value));
// this.successArr.forEach(function(fn) {
// value = fn(value);
// })
// 将value存储在自身
this.value = value;
// 清空队列
this.successArr = [];
};
// 实现失败时候执行的方法
let reject = value => {
// 更改状态
this.status = ‘rejected‘;
// 执行回调函数
this.failArr.forEach(fn => value = fn(value));
// 将value存储在自身
this.value = value;
// 清空队列
this.failArr = [];
}
// 执行回调函数
try {
callback(resolve, reject);
} catch(e) {
// 运行时出现了错误,也就失败了
reject(e);
}
};
// 原型then方法
MyPromise.prototype.then = function(success, fail) {
// 要是处于执行的pending状态,要存储回调函数
// 判断状态
if(this.status === ‘pending‘) {
// 存储 往成功回调函数队列中添加数据
success && this.successArr.push(success);
// 如果fail不是undnefined,我们再往失败回调函数队列中添加数据
fail && this.failArr.push(fail);
} else if(this.status === ‘resolved‘) {
// 立即执行,不需要存储
success && success(this.value);
} else {
// 失败了
fail && fail(this.value);
};
// 返回this
return this;
};
// 创建promise对象
let p = new MyPromise((resolve, reject) => {
console.log(‘start‘);
setTimeout(() => {
// 如果成功执行resovle
resolve(‘执行成功‘);
// 如果失败执行reject
// reject(‘执行失败‘);
}, 1000);
});
// 监听结果
p.then(
(success) => {
console.log(‘success‘, success);
// 前一个then方法的返回值将作为后一个then方法的参数
return ‘第一个监听执行成功then方法的返回值‘;
},
(fail) => {
console.log(‘fail‘, fail);
return ‘第一个监听失败成功then方法的返回值‘;
})
// 链式调用
.then((success) => {
console.log(success);
return ‘第er个监听执行成功then方法的返回值‘;
},
(fail) => {
console.log(fail);
return ‘第er个监听失败成功then方法的返回值‘;
})
.then((success) => {
console.log(success);
return ‘第三个监听执行成功then方法的返回值‘;
},
(fail) => {
console.log(fail);
return ‘第三个监听失败成功then方法的返回值‘;
})
</script>
标签:需要 code === fail 方法参数 cat 表示 stat function
原文地址:https://www.cnblogs.com/yess/p/13129951.html