手写一个符合Promise/A+规范的Promise
Promise/A+规范
参考文献这个博主真的写的特别好
首先我们应该知道的事情:
在Promise中:
- 首先我们在调用Promise的时候会返回一个Promise对象
- 构建Promise时,会给其传入一个函数参数executor,这个函数立即执行
- 当这个函数运行成功之后,会调用resolve函数,如果运行失败,会调用rejected函数
- Promise状态不可逆,不能停止,同时调用 resolve 函数和 reject 函数,默认会采取第一次调用的结果。
const PENDING = "PENDING";
const FULFILLED = "FULFILLED";
const REJECTED = "REJECTED"
class Promise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [] // 专门存放成功的回调函数
this.onRejectedCallbacks = [] // 专门存放失败的回调函数
//成功调用的函数
let resolved = (value) => {
if (this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
this.onResolvedCallbacks.forEach(fn => { fn() })
}
}
//失败调用的函数
let rejected = (reason) => {
if (this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => { fn() })// 需要让成功的方法依次执行
}
}
//立即执行executor
try {
executor(resolved, rejected)
} catch (error) {
rejected(error)
}
//then方法
}
then(onFulfilled, onRejected) {
if (this.status === FULFILLED) {
onFulfilled(this.value)
}
if (this.status === REJECTED) {
onRejected(this.reason)
}
if (this.status === PENDING) {//如果状态是等待,就将回调函数push到专门存放成功/失败的回调函数
this.onResolvedCallbacks.push(() => { onFulfilled(this.value) })
this.onRejectedCallbacks.push(() => { onRejected(this.reason) })
}
}
}
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('成功');
}, 1000);
}).then(
(data) => {
console.log('success', data)
},
(err) => {
console.log('faild', err)
}
)
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END