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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
| class HD { static PENDING = "pending"; static FULFILLED = "fulfilled"; static REJECTED = "rejected"; constructor(executor) { this.status = HD.PENDING; this.value = null; this.callbacks = []; try { executor(this.resolve.bind(this), this.reject.bind(this)); } catch (error) { this.reject(error); } } resolve(value) { if (this.status == HD.PENDING) { this.status = HD.FULFILLED; this.value = value; setTimeout(() => { this.callbacks.map(callback => { callback.onFulfilled(value); }); }); } } reject(reason) { if (this.status == HD.PENDING) { this.status = HD.REJECTED; this.value = reason; setTimeout(() => { this.callbacks.map(callback => { callback.onRejected(reason); }); }); } }
then(onFulfilled, onRejected) { if (typeof onFulfilled != "function") { onFulfilled = () => this.value; } if (typeof onRejected != "function") { onRejected = () => this.value; }
let promise = new HD((resolve, reject) => { if (this.status == HD.PENDING) { this.callbacks.push({ onFulfilled: value => { this.parse(promise, onFulfilled(value), resolve, reject); }, onRejected: value => { this.parse(promise, onRejected(value), resolve, reject); } }); }
if (this.status == HD.FULFILLED) { setTimeout(() => { this.parse(promise, onFulfilled(this.value), resolve, reject); }); } if (this.status == HD.REJECTED) { setTimeout(() => { this.parse(promise, onRejected(this.value), resolve, reject); }); } }); return promise; }
parse(promise, result, resolve, reject) { if (promise == result) { throw new TypeError("Chaining cycle detected"); }
try { if (result instanceof HD) { result.then(resolve, reject); } else { resolve(result); } } catch (error) { reject(error); } }
static resolve(value) { return new HD((resolve, reject) => { if (value instanceof HD) { value.then(resolve, reject); } else { resolve(value); } }); }
static reject(value) { return new HD((resolve, reject) => { reject(value); }); }
static all(promises) { const values = []; return new HD((resolve, reject) => { promises.forEach(promise => { promise.then( value => { values.push(value); if (values.length == promises.length) { resolve(values); } }, reason => { reject(reason); } ); }); }); }
static race(promises) { return new HD((resolve, reject) => { promises.map(promise => { promise.then( value => { resolve(value); }, reason => { reject(reason); } ); }); }); } }
|