promise就是一个对象,用来传递异步操作的消息。
首先了解一下 promise的用法
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success");
});
});
promise.then(
value => {
console.log(value)
},
reason => {
console.log(reason)
}
);
完成一个promise首先一个Promise构造函数,Promise 的构造函数接收了一个回调函数,这个回调执行器(executor),executor 里面的 resolve, reject 也是两个函数,负责改变 Promise 实例的状态和它的值,then 函数中的回调在状态改变后执行,除此之外 then 还支持链式调用。
class MyPromise {
constructor(executor){
// 校验executor
if(typeof executor !== "function"){
throw new Error('ERROR');
};
this.value = undefined; //终值=>resolve的值
this.reason = undefined;//拒因=>reject的值
this.state = "pending";//状态
this.onFulfilledCallbacks = [];// 成功回调
this.onRejectedCallbacks = [];// 失败回调
const resolve = (value)=>{
// 成功后的一系列操作(状态的改变,成功回调的执行)
if(this.state === "pending"){
this.state = "fulfilled";
this.value = value;
this.onFulfilledCallbacks.forEach(fn=>fn(this.value));
};
};
const reject = (reason)=>{
// 失败后的一系列操作(状态的改变,成功回调的执行)
if(this.state === "pending"){
this.state = "rejected";
this.reason = reason;
this.onRejectedCallbacks.forEach(fn=>fn(this.reason));
}
};
try{
executor(resolve,reject);
}catch(err){
reject(err);
}
}
then(onFulfilled,onRejected){
// onFulfilled未传值或传的值不是function的时候
// 自动把onFulfilled变成一个函数
if(typeof onFulfilled !== "function"){
onFulfilled = value => value;
};
//onRejected未传值或传的值不是function的时候
//自动把onFulfilled变成一个函数,并抛出错误
if(typeof onRejected !== "function"){
onRejected = reason => { throw reason }
};
if(this.state === "pending"){
this.onFulfilledCallbacks.push(
(value)=>{
setTimeout(()=>onFulfilled(value))
}
);
this.onRejectedCallbacks.push(
(reason)=>{
setTimeout(()=>onRejected(reason))
}
);
};
if(this.state === "fulfilled"){
setTimeout(()=>onFulfilled(this.value));
};
if(this.state === "rejected"){
setTimeout(()=>onRejected(this.reason));
};
}
};