实现一个Promise之基础、异步

其实跟着promise a+一步一步,按照顺序实现一个promise并不难,今天先实现最简单的promise和异步resolve。本来想全部一次性写完,想想还是分开走,希望想学的可以敲几遍。 //promise三个状态 const PENDING = 'PENDING'; const FULFILLED = 'FULFILLED'; const REJECTED = 'REJECTED'; class Promise { constructor(executor){ //状态 this.state = PENDING; //成功值 失败值 默认undefined this.value = undefined; this.reason = undefined; //简易发布订阅,实例可以then多次,用数组 this.onResolvedCallbacks = []; this.onRejectedCallbacks = []; //成功方法 let resolve = (value) => { if(this.state === PENDING){ this.state = FULFILLED; this.value = value; this.onResolvedCallbacks.forEach(fn => fn()); } }; //失败方法 let reject = (reason) => { if(this.state === PENDING){ this.state = REJECTED; this.reason = reason; this.onRejectedCallbacks.forEach(fn => fn()); } }; //立即执行,如果有错误直接执行失败方法 try{ executor(resolve, reject); }catch (e) { reject(e); } } //then方法,一个成功函数,一个失败函数 then(onFulfilled, onRejected){ //如果成功,执行成功函数 if(this.state === FULFILLED){ onFulfilled(this.value); }; //如果失败,执行失败函数 if(this.state === REJECTED){ onRejected(this.reason); }; //如果有异步,订阅成功失败函数 if(this.state === PENDING){ this.onResolvedCallbacks.push(() => { onFulfilled(this.value); }); this.onRejectedCallbacks.push(() => { onRejected(this.reason); }); }; } } 最简单的实现,可以理解理解。 image

本文章由javascript技术分享原创和收集

发表评论 (审核通过后显示评论):