js手写'Promise'
Posted wumi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js手写'Promise'相关的知识,希望对你有一定的参考价值。
/* * pending:初始化成功 * fulfilled:成功 * rejected:失败 * */ function Promise(executor) {// 执行器 this.status = ‘pending‘; this.value = undefined; this.reason = undefined; this.fulfilledCallback = []; this.rejectCallback = []; let resolve = (value)=>{ if(this.status==‘pending‘){ this.status = ‘resolve‘; this.value = value; this.fulfilledCallback.forEach(fn=>fn()) } }; let reject = (reason)=>{ if(this.status ==‘pending‘){ this.status = ‘reject‘; this.reason = reason; this.rejectCallback.forEach(fn=>fn()) } }; try{ executor(resolve,reject) }catch(e){ reject(e) } } Promise.prototype.then = function (onfulfilled,onrejected) { if(this.status == ‘resolve‘){ onfulfilled(this.value) } if(this.status == ‘reject‘){ onrejected(this.reason) } if(this.status == ‘pending‘){ this.fulfilledCallback.push(()=>{ onfulfilled(this.value) }); this.rejectCallback.push(()=>{ onrejected(this.reason) }) } }; var a = new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(10) }) }); a.then((res)=>{ console.log(res); });
以上是关于js手写'Promise'的主要内容,如果未能解决你的问题,请参考以下文章
手写promise,promise.all,promise.race
VSCode自定义代码片段12——JavaScript的Promise对象