本文共 1453 字,大约阅读时间需要 4 分钟。
class MyPromise{ constructor(callback){ this.status = 'pendding'; this.result = null; this.err = null; this.resolveFn = null; this.rejectFn = null; this.resolve = function(val){ if(this.status === 'pendding'){ this.status = 'resolve'; this.result = val; this.resolveFn && this.resolveFn(this.result); } } this.reject = function(err){ if(this.status === 'pendding'){ this.status = 'reject'; this.err = err; this.rejectFn && this.rejectFn(this.err); } } callback(this.resolve.bind(this),this.reject.bind(this)); } then(callback){ if(this.status === 'resolve' ){ callback(this.result); }else{ this.resolveFn = callback; } return this; } catch(callback){ if(this.status === 'reject' ){ callback(this.err); }else{ this.rejectFn = callback; } } }
调用
let p = new MyPromise((resolve,reject) => { setTimeout(() => { resolve(123); reject(456); },1000) }) p.then(res => { console.log(res); }).catch(err => { console.log(err); })
转载地址:http://roven.baihongyu.com/