手写实现简易版Promise
//1.定义三种状态 const PENDING = 'pending' const RESOLVED = 'resolved' const REJECTED = 'rejected' function MyPromisr(fn){ //重命名this,防止接下来找不到正确的this const that = this that.state = PENDING //初始状态为等待 that.value = null //value用于保存resolved或rejoiced传入的值 that.resolvedCallbacks = [] //成功请求后的回调数组 //定义完成的回调函数 function resolved(value) { // 只有在等待状态才可以改变状态 if (that.state === PENDING) { that.state = RESOLVED that.value = value that.resolvedCallbacks.map(cb => cb(that.value)) } } //定义拒绝的回调函数 function rejected(value) { // 只有在等待状态才可以改变状态 if (that.state === PENDING) { that.state = REJECTED that.value = value that.rejectedCallbacks.map(cb => cb(that.value)) } } // 定义了两种状态的回调函数后,执行mypromise传参的函数 try { fn(resolved,rejected) } catch (e) { rejected(e) } } // 定义then MyPromise.prototype.then = function(onFulfilled,onRejected){ const that = this onFulfilled = typeof onFulfilled === 'function' ? onFulfilled :v => v onRejected = typeof onRejected === 'function' ? onRejected : r => { throw r } if (that.state === PENDING) { that.resolvedCallbacks.push(onFulfilled) that.rejectedCallbacks.push(onRejected) } if (that.state === RESOLVED) { onFulfilled(that.value) } // console.log(that.state,'has change') if (that.state === REJECTED) { onRejected(that.value) } } //调用 new MyPromise((resolved,rejected) => { setTimeout(()=>{ resolved(1) rejected(2) },0) }).then(value=>{ console.log(value) },value=>{ console.log(value) })
相关推荐
前端开发Kingcean 2020-06-11
前端开发Kingcean 2020-05-29
89500297 2020-04-29
往后余生 2020-09-17
CXsilent 2020-09-16
webgm 2020-08-16
Lophole 2020-06-28
sqliang 2020-06-14
xcguoyu 2020-06-13
徐建岗网络管理 2020-06-11
cbao 2020-06-10
yezitoo 2020-06-06
bigname 2020-06-04
xiaofanguan 2020-05-29
ELEMENTS爱乐小超 2020-05-28
皖林 2020-05-11
wbczyh 2020-05-03