Promise是一个类,本身是同步的,then方法是异步的。
1、测试代码
let Prmoise = require("./17.promise");
let p = new Promise((resolve, reject) => {
setTimeout(() => {
reject(123);
}, 1000);
});
p.then(
(data) => {
console.log("s", data);
},
(err) => {
console.log("e", err);
}
);
2、手写promise.js
class Promise {
constructor(executor) {
this.status = "pending";
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks=[]; // 存放成功的回调
this.onRejectedCallbacks=[]; // 存放失败的回调
let resolve = (data) => {
if (this.status === "pending") {
this.value = data;
this.status = "resolved";
this.onResolvedCallbacks.forEach(fn=>fn())
}
};
let reject = (reason) => {
if (this.status === "pending") {
this.reason = reason;
this.status = "rejected";
this.onRejectedCallbacks.forEach(fn=>fn());
}
};
try {
// 执行时,可能发生异常
executor(resolve, reject);
} catch (e) {
reject(e); //promise失败了
}
}
then(onFufilled, onRejected) {
if (this.status === "resolved") {
onFufilled(this.value);
}
if (this.status === "rejected") {
onRejected(this.reason);
}
// 当前既没有完成,也没有失败
if(this.status==="pending"){
this.onResolvedCallbacks.push(()=>{
//...todo
onFufilled(this.value) // 存放成功的回调
});
this.onRejectedCallbacks.push(()=>{
onRejected(this.reason); // 存放失败的回调
})
}
}
}
module.exports = Promise;