|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const DEFERRED_PENDING = 0; |
| 4 | +const DEFERRED_RESOLVED = 1; |
| 5 | +const DEFERRED_REJECTED = 2; |
| 6 | + |
| 7 | +const deferred = () => ({ |
| 8 | + value: undefined, |
| 9 | + onDone: null, |
| 10 | + onFail: null, |
| 11 | + status: DEFERRED_PENDING, |
| 12 | + isPending() { |
| 13 | + return this.status === DEFERRED_PENDING; |
| 14 | + }, |
| 15 | + isResolved() { |
| 16 | + return this.status === DEFERRED_RESOLVED; |
| 17 | + }, |
| 18 | + isRejected() { |
| 19 | + return this.status === DEFERRED_REJECTED; |
| 20 | + }, |
| 21 | + done(callback) { |
| 22 | + this.onDone = callback; |
| 23 | + if (this.isResolved()) callback(this.value); |
| 24 | + return this; |
| 25 | + }, |
| 26 | + fail(callback) { |
| 27 | + this.onFail = callback; |
| 28 | + if (this.isRejected()) callback(this.value); |
| 29 | + return this; |
| 30 | + }, |
| 31 | + resolve(value) { |
| 32 | + this.value = value; |
| 33 | + if (this.onDone) this.onDone(value); |
| 34 | + return this; |
| 35 | + }, |
| 36 | + reject(value) { |
| 37 | + this.value = value; |
| 38 | + if (this.onFail) this.onFail(value); |
| 39 | + return this; |
| 40 | + } |
| 41 | +}); |
| 42 | + |
| 43 | +// Usage |
| 44 | + |
| 45 | +const persons = { |
| 46 | + 10: 'Marcus Aurelius', |
| 47 | + 11: 'Mao Zedong', |
| 48 | + 12: 'Rene Descartes', |
| 49 | +}; |
| 50 | + |
| 51 | +const getPerson = id => { |
| 52 | + const result = deferred(); |
| 53 | + setTimeout(() => { |
| 54 | + const name = persons[id]; |
| 55 | + if (name) result.resolve({ id, name }); |
| 56 | + else result.reject(new Error('Person is not found')); |
| 57 | + }, 1000); |
| 58 | + return result; |
| 59 | +}; |
| 60 | + |
| 61 | +const d1 = getPerson(10) |
| 62 | + .done(value => console.log('Resolved d1', value)) |
| 63 | + .fail(error => console.log('Resolved d1', error)); |
| 64 | +console.dir({ d1 }); |
| 65 | + |
| 66 | +const d2 = getPerson(20) |
| 67 | + .done(value => console.log('Resolved d2', value)) |
| 68 | + .fail(error => console.log('Resolved d2', error.message)); |
| 69 | +console.dir({ d2 }); |
0 commit comments