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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| const PENDING = "pending", FULFILLED = "fulfilled", REJECTED = "rejected";
class MyPromise { constructor(executor) { this.state = PENDING; this.value = undefined; this.reason = undefined; this.onResolvedCallbacks = []; this.onRejectedCallbacks = [];
let resolve = value => { if (this.state === PENDING) { this.state = FULFILLED; this.value = value; this.onResolvedCallbacks.forEach(fn => fn()); } };
let reject = reason => { if (this.state === PENDING) { this.state = REJECTED; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; try { executor(resolve, reject); } catch (err) { reject(err); } }
then(onFulFilled, onRejected) { let p2 = new MyPromise((resolve, reject) => { let x; if (this.state === FULFILLED) { setTimeout(() => { x = onFulFilled(this.value);
resolvePromise(p2, x, resolve, reject);
}, 0); }
if (this.state === REJECTED) { x = onRejected(this.reason); resolvePromise(p2, x, resolve, reject); }
if (this.state === PENDING) { this.onResolvedCallbacks.push(() => { x = onFulFilled(this.value); resolvePromise(p2, x, resolve, reject); }); this.onRejectedCallbacks.push(() => { x = onRejected(this.reason); resolvePromise(p2, x, resolve, reject); }); } });
return p2; } }
function resolvePromise(p2, x, resolve, reject) { if (p2 === x) { return new Error("引用错误"); } if ((typeof x === "object" && x !== null) || typeof x === "function") { try { let then = x.then; if (typeof then === "function") { then.call( x, y => { resolvePromise(p2, y, resolve, reject); }, err => { reject(err); } ); } } catch (err) { reject(err); } } else { resolve(x); } }
|