0%
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
| const PENDING = 'pending'; const FULFILLED = 'fulfilled'; const REJECTED = 'rejected';
function myPromise(fn) { const self = this; this.state = PENDING; this.value = []; this.resolveCallbacks = []; this.rejectCallbacks = []; function resolve(value) { if (value instanceof myPromise) { return value.then(resolve, reject); } setTimeout(() => { if (this.state === PENDING) { this.state = FULFILLED; this.value = value; resolveCallbacks.forEach(callback=>callback(value)); } }, 0); } function reject(reason) { setTimeout(() => { if (this.state === PENDING) { this.state = REJECTED; this.value = reason; resolveCallbacks.forEach(callback=>callback(reason)); } }, 0); } try{ fn(resolve, reject); } catch (err) { reject(err); } }
|