diff --git "a/8. \345\274\202\346\255\245\345\244\204\347\220\206/8-6. [\346\211\251\345\261\225]\346\211\213\345\206\231Promise/MyPromise.js" "b/8. \345\274\202\346\255\245\345\244\204\347\220\206/8-6. [\346\211\251\345\261\225]\346\211\213\345\206\231Promise/MyPromise.js" index f60ead1dabd6937517373b2327ea64076b4dde2d..f73247337b32942f640e85d0f4cfe93ffba3a83d 100644 --- "a/8. \345\274\202\346\255\245\345\244\204\347\220\206/8-6. [\346\211\251\345\261\225]\346\211\213\345\206\231Promise/MyPromise.js" +++ "b/8. \345\274\202\346\255\245\345\244\204\347\220\206/8-6. [\346\211\251\345\261\225]\346\211\213\345\206\231Promise/MyPromise.js" @@ -1,7 +1,7 @@ // 记录Promise的三种状态 -const PENDING = 'pending'; -const FULFILLED = 'fulfilled'; -const REJECTED = 'rejected'; +const PENDING = "pending"; +const FULFILLED = "fulfilled"; +const REJECTED = "rejected"; /** * 运行一个微队列任务 @@ -15,12 +15,12 @@ function runMicroTask(callback) { if (globalThis.process && globalThis.process.nextTick) { process.nextTick(callback); } else if (globalThis.MutationObserver) { - const p = document.createElement('p'); + const p = document.createElement("p"); const observer = new MutationObserver(callback); observer.observe(p, { childList: true, // 观察该元素内部的变化 }); - p.innerHTML = '1'; + p.innerHTML = "1"; } else { setTimeout(callback, 0); } @@ -32,7 +32,7 @@ function runMicroTask(callback) { * @returns */ function isPromise(obj) { - return !!(obj && typeof obj === 'object' && typeof obj.then === 'function'); + return !!(obj && typeof obj === "object" && typeof obj.then === "function"); } class MyPromise { @@ -94,7 +94,7 @@ class MyPromise { return; } - if (typeof executor !== 'function') { + if (typeof executor !== "function") { // 传递后续处理并非一个函数 this._state === FULFILLED ? resolve(this._value) : reject(this._value); return; @@ -161,6 +161,12 @@ class MyPromise { // 目前状态已经更改 return; } + if (isPromise(value)) { + runMicroTask(() => { + value.then(this._resolve.bind(this), this._reject.bind(this)); + }); + return; + } this._state = newState; this._value = value; this._runHandlers(); // 状态变化,执行队列 @@ -285,4 +291,3 @@ class MyPromise { }); } } -