🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**简易Promise:**简易`Promise`并不完全符合`Promise/A+`规范,但面试时能写出简易`Promise`算是已经过关了。 ``` function MyPromise(fn) { let _this = this _this.state = 'pending'_this.value = null _this.reson = null _this.onFulfilledCallbacks = [] _this.onRejectedCallbacks = [] function resolve(value) { if (_this.state === 'pending') { _this.value = value _this.state = 'fulled' _this.onFulfilledCallbacks.map(fn = >fn()) } } function reject(reson) { if (_this.state === 'pending') { _this.reson = reson _this.state = 'rejected' _this.onRejectedCallbacks.map(fn = >fn()) } } fn(resolve, reject) } MyPromise.prototype.then = function(suc, err) { let _this = this if (_this.state === 'pending') { _this.onFulfilledCallbacks.push(() = >{ suc(_this.value); }); _this.onRejectedCallbacks.push(() = >{ err(_this.value); }) } if (_this.state === 'fulled') { suc(_this.value) } if (_this.state === 'rejected') { err(_this.reson) } } let p = new MyPromise(function(resolve, reject) { setTimeout(() = >{ resolve('oj8k') }, 1000) }) p.then(suc = >{ console.log(suc) }, err = >{ console.log(err) }); ```