手写 Promise 也是面试的一个特色项目,本篇将用简洁的代码带你了解 Promise 的异步链式调用。

非标准 A+ 规范,想要深入的可以去看 A+ 规范实现的 Promise

Promise 代码

// promise 运行则执行回调函数,
// resolve 函数被执行的时候调用当前实例下挂载的 then 函数。
// 参数1:回调函数
function Promise2(executor) {
const self = this;
self.onResolvedCallback = [];
// 定义 resolve 函数,接受参数 value
// resolve 的作用为执行当前实例下的所有 then 函数
function resolve(value) {
// A+ 规范
self.value = value;
// 此时的 callback 为执行 then 的时候传入的回调
self.onResolvedCallback.forEach(callback => callback());
}
executor(resolve.bind(this));
}

Promise2.prototype.then = function (onResolved) {
// 此时的 this 指向和下面的promise中 this 指向是两个不同的对象,切勿混乱
const self = this;
// 记住这里的 resolve 是为了调用下一次的 then,执行了才会调用
return new Promise2(function (resolve) {
// push 到 then 回调栈中,方便 promise 执行 resolve 的时候执行他

self.onResolvedCallback.push(function () {
// 执行 then 的回调函数,返回值分两种情况,一种是正常返回和返回异步的 promise
const result = onResolved(self.value);
// 所以这里需要判断回调函数的返回值是否在promise的原型链上
if (result instanceof Promise2) {
// 此时的 result 为 promise,所以我们需要等他执行完毕之后才能执行当前 promise 的下一个 then 的回调
// 所以在 result 的第一个 then 函数执行的时候即可
result.then(resolve)
} else {
// 如果是正常的返回值的话,把返回值带个下一个 then 函数就好
resolve(result);
}
})
})
}

原文推荐
https://juejin.im/post/5e6f4579f265da576429a907#heading-0