promise是前端解决异步的一个重要的东西。其主要使用如下:
const p1 = new Promise((resolve, reject) => {
// 此处走then方法
resolve(111)
// 此处走catch方法
// reject(222)
})
p1.then((res) => {
console.log(res);
}).catch(err => {
console.log(err);
})
请自己实现一个Promise方法,可以满足以上的功能。
class MyPromise {
constructor(executor) {
executor(this.resolve.bind(this), this.reject.bind(this))
}
state = 'pending'
// 成功的值
value = null
// 失败的值
reason = null
// 当走到then/catch方法的时候,如果状态没变化,就暂时先声明一个变量去缓存方法,等到状态变化的时候再去执行
onFulfilledCallbackList = []
onRejectedCallbackList = []
resolve(value) {
if (this.state !== 'pending') return;
this.state = 'fulfilled'
this.value = value
this.onFulfilledCallbackList.forEach(callback => callback(value))
this.onFulfilledCallbackList = []
}
reject(reason) {
if (this.state !== 'pending') return;
this.state = 'rejected'
this.reason = reason
this.onRejectedCallbackList.forEach(callback => callback(reason))
this.onRejectedCallbackList = []
}
then(onFulFilled, onRejected) {
return new MyPromise((res, rej) => {
if (this.state === 'fulfilled') {
res(onFulFilled(this.value))
};
if (this.state === 'rejected') {
rej(onRejected(this.reason))
};
if (this.state === 'pending') {
this.onFulfilledCallbackList.push(onFulFilled)
this.onRejectedCallbackList.push(onRejected)
};
})
}
}
const myP1 = new MyPromise((resolve, reject) => {
console.log('立即执行');
resolve(111)
// setTimeout(() => {
// resolve(111)
// }, 3000)
}).then(res => {
console.log('成功了', res);
}, err => {
console.log('失败了', err);
}).then(res => {
console.log('链式调用then方法', res);
})