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
| class Promise { #PromiseState = "pending"; #PromiseResult = undefined; constructor(fn) { const resolve = (response) => { this.#PromiseState = "fulfilled"; this.#PromiseResult = response; }; const reject = (reason) => { this.#PromiseState = "rejected"; this.#PromiseResult = reason; }; fn.call(this, resolve, reject); } then(onfulfilled, onrejected) { return new Promise((resolve, reject) => { try { let result; if (this.#PromiseState === "fulfilled" && typeof onfulfilled === "function") { result = onfulfilled(this.#PromiseResult); } else if (this.#PromiseState === "rejected" && typeof onfulfilled === "function") { result = onrejected(this.#PromiseResult); } resolve(result); } catch (e) { reject(e); } }); } catch(onrejected) { return new Promise((resolve, reject) => { try { resolve(onrejected(this.#PromiseResult)); } catch (e) { reject(e); } }); } } Promise.resolve = (data) => new Promise((resolve) => resolve(data)); Promise.reject = (data) => new Promise((_, reject) => reject(data)); Promise.all = (promises) => { const result = []; let fulfilledCount = 0; return new Promise((resolve, reject) => { promises.forEach((p, i) => { if (!(p instanceof Promise)) { fulfilledCount += 1; result[i] = p; } else { p.then( (data) => { fulfilledCount += 1; result[i] = data; if (fulfilledCount >= promises.length) { resolve(result); } }, (data) => { reject(data); } ); } }); }); };
var p1 = new Promise((resolve, reject) => resolve(1.1)); p1.then((data) => { console.log(2.1, data); return 2.1; }, (data) => { console.log(2.2, data); return 2.2; }) .then((data) => { console.log(3.1, data); return 3.1; }, (data) => { console.log(3.2, data); return 3.2; });
var p2 = new Promise((resolve, reject) => reject(1.2)); p2.then((data) => { console.log(2.1, data); return 2.1; }, (data) => { console.log(2.2, data); throw 2.2; }) .then((data) => { console.log(3.1, data); return 3.1; }, (data) => { console.log(3.2, data); return 3.2; });
var p3 = new Promise((resolve, reject) => resolve(1.1)); p3.then((data) => { console.log(2.1, data); throw 2.1; }, (data) => { console.log(2.2, data); return 2.2; }) .then((data) => { console.log(3.1, data); return 3.1; }, (data) => { console.log(3.2, data); return 3.2; });
var p4 = new Promise((resolve, reject) => resolve(1.1)); p4.then((data) => { console.log(2.1, data); throw 2.1; }) .catch((data) => { console.log("catch", data); throw "catch error"; });
Promise.all([1, Promise.resolve(2)]).then((values) => { console.log(values); }); Promise.all([1, Promise.reject('err')]).catch((err) => { console.log(err); });
|