手写 Promise
也是面试的一个特色项目,本篇将用简洁的代码带你了解 Promise
的异步链式调用。
非标准 A+ 规范,想要深入的可以去看 A+ 规范实现的 Promise
Promise
代码
function Promise2(executor) { const self = this; self.onResolvedCallback = []; function resolve(value) { self.value = value; self.onResolvedCallback.forEach(callback => callback()); } executor(resolve.bind(this)); }
Promise2.prototype.then = function (onResolved) { const self = this; return new Promise2(function (resolve) { self.onResolvedCallback.push(function () { const result = onResolved(self.value); if (result instanceof Promise2) { result.then(resolve) } else { resolve(result); } }) }) }
|
原文推荐
https://juejin.im/post/5e6f4579f265da576429a907#heading-0