1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| function MyPromise(fn) { let state = "pending"; let value = null; const callbacks = [];
this.then = function (onFulfilled) { return new MyPromise((resolve, reject) => { handle({ onFulfilled, resolve, }); }); };
function handle(callback) { if (state === "pending") { callbacks.push(callback); return; }
if (state === "fulfilled") { if (!callback.onFulfilled) { callback.resolve(value); return; } const ret = callback.onFulfilled(value); callback.resolve(ret); } } function resolve(newValue) { const fn = () => { if (state !== "pending") return;
state = "fulfilled"; value = newValue; handelCb(); };
queueMicrotask(fn); }
function handelCb() { while (callbacks.length) { const fulfiledFn = callbacks.shift(); handle(fulfiledFn); } } fn(resolve); } new MyPromise((resolve, reject) => { debugger; setTimeout(() => { resolve(20); }, 0); }).then((data) => { console.log(data); }); console.log(1); setTimeout(() => { console.log(2); }, 0);
|