带你读《现代Javascript高级教程》二十七、实现符合Promise/A+规范的Promise(1)https://developer.aliyun.com/article/1349507?groupCode=tech_library
步骤 3: 实现 resolve 和 reject 函数
我们需要实现 resolve 和 reject 函数,用于将 Promise 的状态从 'pending' 转换为 'fulfilled' 或 'rejected'。resolve 函数将传递一个值来兑现 Promise,而 reject 函数将传递一个原因来拒绝 Promise。
function MyPromise(executor) { var self = this; self.state = 'pending'; self.value = undefined; self.reason = undefined; self.onFulfilledCallbacks = []; self.onRejectedCallbacks = []; function resolve(value) { if (self.state === 'pending') { self.state = 'fulfilled'; self.value = value; self.onFulfilledCallbacks.forEach(function(callback) { callback(self.value); }); } } function reject(reason) { if (self.state === 'pending') { self.state = 'rejected'; self.reason = reason; self.onRejectedCallbacks.forEach(function(callback) { callback(self.reason); }); } } try { executor(resolve, reject); } catch (e) { reject(e); }}
步骤 4: 实现 then 方法
接下来,我们需要实现 then 方法,用于注册成功和失败的回调函数,并返回一个新的 Promise。then 方法接受两个参数:成功回调函数和失败回调函数。
function MyPromise(executor) { var self = this; self.state = 'pending'; self.value = undefined; self.reason = undefined; self.onFulfilledCallbacks = []; self.onRejectedCallbacks = []; function resolve(value) { if (self.state === 'pending') { self.state = 'fulfilled'; self.value = value; self.onFulfilledCallbacks.forEach(function(callback) { callback(self.value); }); } } function reject(reason) { if (self.state === 'pending') { self.state = 'rejected'; self.reason = reason; self.onRejectedCallbacks.forEach(function(callback) { callback(self.reason); }); } } try { executor (resolve, reject); } catch (e) { reject(e); }} MyPromise.prototype.then = function(onFulfilled, onRejected) { var self = this; onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : function(value) { return value; }; onRejected = typeof onRejected === 'function' ? onRejected : function(reason) { throw reason; }; var newPromise = new MyPromise(function(resolve, reject) { // TODO: 实现 then 方法的其余部分 }); return newPromise;};
带你读《现代Javascript高级教程》二十七、实现符合Promise/A+规范的Promise(3)https://developer.aliyun.com/article/1349505?groupCode=tech_library