手写Promsie
代码
index.js
const MyPromise = require('./Promsie.js')
// what why how
// 三种状态:等待态 pedding 成功态fullfilled 失败态 rejected
// 最终一种状态:成功/失败
const p = new MyPromise(function (resolve, reject) {
setTimeout(function () {
resolve(1)
},1000)
})
p.then(function(data) {
console.log(data);
}, function (err) {
console.log(err);
})
Promsie.js
代码
const PEDDING = 'PEDDING'; // 等待
const FULLFILLED = 'FULLFILLED'; // 成功
const ONREJECTED = 'ONREJECTED' // 失败
class Promise {
// 构造函数
constructor (executor) {
this.status = PEDDING; // 默认等待
this.value = undefined; // 成功的值
this.reason = undefined; // 失败的值
// 成功回调队列
this.onFullfilledCallBacks = [];
// 失败回调队列
this.onRejectedCallBacks = [];
// 成功
const resolve = (value)=>{
if (this.status === PEDDING) {
// 变成成功态
this.status = FULLFILLED;
this.value = value;
this.onFullfilledCallBacks.forEach(fn=>fn())
}
}
// 失败
const reject = (reason) =>{
if (this.status === PEDDING ) {
this.status = ONREJECTED;
this.reason = reason;
this.onRejectedCallBacks.forEach(fn=>fn())
}
}
executor(resolve,reject)
}
then (onFullfilled, onRejected) {
// 成功
if (this.status === FULLFILLED) {
onFullfilled(this.value)
}
// 失败
if (this.status === ONREJECTED ) {
onRejected(this.reason)
}
// 等待
if (this.status === PEDDING) {
// 成功
this.onFullfilledCallBacks.push(()=>{
onFullfilled(this.value)
})
// 失败
this.onRejectedCallBacks.push(()=>{
onRejected(this.reason)
})
}
}
}
// const p = new Promise()
module.exports = Promise;