Promise是前端面试中经常问的问题,如果你能根据PromiseA+的规范,写出符合规范的源码,那么我想,对于面试中的Promise相关的问题,都能够给出比较完美的答案。

不说了,上代码:
/**
* 使用 class 实现封装 Promise
*
*
*/
class myPromise {
constructor (executor) {
this.status = "pending"; // 定义状态改变前的初始状态
this.refulfilled = undefined; // 定义状态为 resolved 前的初始状态
this.rejected = undefined; // 定义状态为 rejected 前的初始状态
this.onFulfilled = []; // 成功的回调
this.onRejected = [] // 失败的回调
let resolve = (value) => {
if (this.status === "pending") {
this.status = "resolved";
this.value = value;
this.onFulfilled.forEach(function (fn) { fn(value) })
}
}
let reject = (reason) => {
if (this.status === "pending") {
this.status = "rejected";
this.reason = reason;
this.onRejected.forEach(function (fn) { fn(reason) })
}
}
try {
executor(resolve, reject)
} catch(e) {
reject(e)
}
}
then (onFulfilled, onRejected) {
let self = this;
if (this.status === "resolved") {
onFulfilled(this.value)
} else if (this.status === "rejected") {
onRejected(this.reason)
} else {
this.onFulfilled.push(function () {
onFulfilled(self.value)
})
this.onRejected.push(function () {
onRejected(self.reason)
})
}
}
}
// 使用
let axios = function () {
return new myPromise((resolve, reject) => {
setTimeout(() => {
resolve('取值 OK')
console.log('成功')
}, 2000)
})
}
// 返回值
axios().then((val) => {
console.log('正确', val)
}, (err) => {
console.log('出错', err)
})
console.log(new myPromise)end