4_JS的Promise相关
1、Promise的底层代码原理
爱了爱了
摘自知乎 https://zhuanlan.zhihu.com/p/183801144
1 const PENDING = 'PENDING'; 2 const FULFILLED = 'FULFILLED'; 3 const REJECTED = 'REJECTED'; 4 5 class Promise { 6 constructor(executor) { 7 this.status = PENDING; 8 this.value = undefined; 9 this.reason = undefined; 10 // 存放成功的回调 11 this.onResolvedCallbacks = []; 12 // 存放失败的回调 13 this.onRejectedCallbacks= []; 14 15 let resolve = (value) => { 16 if(this.status === PENDING) { 17 this.status = FULFILLED; 18 this.value = value; 19 // 依次将对应的函数执行 20 this.onResolvedCallbacks.forEach(fn=>fn()); 21 } 22 } 23 24 let reject = (reason) => { 25 if(this.status === PENDING) { 26 this.status = REJECTED; 27 this.reason = reason; 28 // 依次将对应的函数执行 29 this.onRejectedCallbacks.forEach(fn=>fn()); 30 } 31 } 32 33 try { 34 executor(resolve,reject) 35 } catch (error) { 36 reject(error) 37 } 38 } 39 40 then(onFulfilled, onRejected) { 41 if (this.status === FULFILLED) { 42 onFulfilled(this.value) 43 } 44 45 if (this.status === REJECTED) { 46 onRejected(this.reason) 47 } 48 49 if (this.status === PENDING) { 50 // 如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行 51 this.onResolvedCallbacks.push(() => { 52 onFulfilled(this.value) 53 }); 54 55 // 如果promise的状态是 pending,需要将 onFulfilled 和 onRejected 函数存放起来,等待状态确定后,再依次将对应的函数执行 56 this.onRejectedCallbacks.push(()=> { 57 onRejected(this.reason); 58 }) 59 } 60 } 61 }
2、自己手写一个
1 const p =new Promise(function(resolve,reject){ 2 setTimeout(function(){ 3 let data = 'kkkk' 4 resolve(data) 5 },2000) 6 }) 7 8 p.then(function(value){ 9 console.log('success', value ) 10 },function(reason){ 11 console.log('faild',reason) 12 })

浙公网安备 33010602011771号