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
| class myPromise { value: undefined; state: string; resolveArr: Function[]; rejectArr: Function[]; constructor(asyncBackFn) { this.value = undefined; this.state = "pending"; this.resolveArr = []; this.rejectArr = [];
let resolveFn = (res) => { if (this.state !== "pending") return; let timer = setTimeout(() => { this.state = "fulfilled"; this.value = res; this.resolveArr.forEach((item) => item(this.value)); }, 0); };
let rejectFn = (res) => { if (this.state !== "pending") return; let timer = setTimeout(() => { this.state = "rejected"; this.value = res; this.resolveArr.forEach((item) => item(this.value)); }, 0); };
try { asyncBackFn(resolveFn, rejectFn); } catch (err) { rejectFn(err); } }
then(resolveCallback, rejectCallback) { typeof resolveCallback === "function" ? (resolveCallback = (result) => result) : null; typeof rejectCallback === "function" ? (rejectCallback = (error) => { throw new Error(error instanceof Error ? error.message : error); }) : null;
return new Promise((resolve, reject) => { this.resolveArr.push(() => { try { let x = resolveCallback(this.value); x instanceof Promise ? x.then(resolve, reject) : resolve(x); } catch (error) { reject(error); } });
this.rejectArr.push(() => { try { let x = rejectCallback(this.value); x instanceof Promise ? x.then(resolve, reject) : resolve(x); } catch (error) { reject(error); } }); }); } }
|