手写一个 Promise
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var Promise = new Promise((resolve, reject) => { if () { resolve(value); } else { reject(error); } }); Promise.then( function (value) { }, function (value) { } );
|
使用 class 手写一个 Promise
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
| class Promise { constructor(executer) { this.status = "pending"; this.value = undefined; this.reason = undefined; let resolveFn = value => { if (this.status == pending) { this.status = "resolve"; this.value = value; } }; let rejectFn = reason => { if (this.status == pending) { this.status = "reject"; this.reason = reason; } }; try { executer(resolve, reject); } catch (e) { reject(e); } } then(onFufilled, onReject) { if ((this.status = "resolve")) { onFufilled(this.value); } if ((this.status = "reject")) { onReject(this.reason); } } }
|