零、前言
1 3状态,pending、fulfiled(resolved)、rejected。3选一! 任意时刻只能处于其中的一种状态。
2 2过程,只能 pending->resolved 或 pending->rejected。不可逆、只能 2选1 !
3 promise
的then
方法接收两个可选参数,表示该promise
状态改变时的回调(promise.then(onFulfilled, onRejected
))。then
方法返回一个promise
。then
方法可以被同一个promise
调用多次。
一、Promise简单实现
1 整体代码
function MyPromise(executor){
console.log('构造开始');
let self = this; // 有啥用??
self.status = 'pending';
self.data;
self.error;
self.resArr = [];
self.rejArr = [];
// 定义 resolve 函数,放于 执行器 executor函数 中。这是 成功 的 回调函数!
function resolve(data){
self.data = data; // 此处 this 为 window, 所以要使用 self !!
// 好像不用异步也行??!!区别??
// self.resArr.forEach(fn => {
// fn(data)
// })
// 注意用到了异步 ?!!
setTimeout(function(){ // 别忘了 setTimeout 第一个参数是函数, 所以要加上 function() !
self.resArr.forEach(fn => { // 为啥是一个数组,一般来说 resolve 只有一个?
fn(data); // 带上数据!!
})
}, 0)
}
function reject(error){
self.error = error;
setTimeout(function () {
self.rejArr.forEach(fn => {
fn(error);
})
}, 0)
}
try{
executor(resolve, reject);
}catch (e) {
reject(e) // 好像有点东西!!所以说执行器自带 try...catch 块
}
console.log('构造结束');
}
MyPromise.prototype.then = function (res, rej) {
// 为啥时放入数组??!!
this.resArr.push(res);
this.rejArr.push(rej);
}
console.log(1)
new MyPromise(function (res, rej) {
setTimeout(function () {
res(6666);
},1000)
})
.then(data => {
console.log(data)
})
console.log(4)
2 重点再次提醒:时刻记住一句话,resolve
函数被调用时会触发then方法中注册的回调函数,从上面这个案例可以充分的体现