带你读《现代Javascript高级教程》二十七、实现符合Promise/A+规范的Promise(2)https://developer.aliyun.com/article/1349506?groupCode=tech_library
步骤 5: 处理 Promise 状态转换和回调执行
我们需要在 then 方法中处理 Promise 的状态转换和回调的执行。根据当前 Promise 的状态,我们可以立即执行回调函数或将回调函数添加到相应的回调数组中。
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) { function handleFulfilled(value) { try { var x = onFulfilled(value); resolvePromise(newPromise, x, resolve, reject); } catch (e) { reject(e); } } function handleRejected(reason) { try { var x = onRejected(reason); resolvePromise(newPromise, x, resolve, reject); } catch (e) { reject(e); } } if (self.state === 'fulfilled') { setTimeout(function() { handleFulfilled(self.value); }, 0); } else if (self.state === 'rejected') { setTimeout(function() { handleRejected(self.reason); }, 0); } else if (self.state === 'pending') { self.onFulfilledCallbacks.push(function(value) { setTimeout(function() { handleFulfilled(value); }, 0); }); self.onRejectedCallbacks.push(function(reason) { setTimeout(function() { handleRejected(reason); }, 0); }); } }); return newPromise;};
步骤 6: 解析 Promise
最后,我们需要实现 resolvePromise 函数,用于解析 Promise。它会处理 thenable 和非 thenable 值,并根据其状态执行相应的处理。
function resolvePromise(promise, x, resolve, reject) { if (promise === x) { reject(new TypeError('Circular reference detected.')); } if (x && typeof x === 'object' || typeof x === 'function') { var called = false; try { var then = x.then; if (typeof then === 'function') { then.call( x, function(y) { if (!called) { called = true; resolvePromise(promise, y, resolve, reject); } }, function(r) { if (!called) { called = true; reject(r); } } ); } else { resolve(x); } } catch (e) { if (!called) { called = true; reject(e); } } } else { resolve(x); }}
带你读《现代Javascript高级教程》二十七、实现符合Promise/A+规范的Promise(4)https://developer.aliyun.com/article/1349504?groupCode=tech_library