手写Promise A+ 规范
程序员文章站
2022-06-22 15:18:58
基于ES6语法手写promise A+ 规范,源码实现 class Promise { constructor(excutorCallBack) { this.status = 'pending'; this.value = undefined; this.fulfilledAry = []; th ......
基于es6语法手写promise a+ 规范,源码实现
class promise { constructor(excutorcallback) { this.status = 'pending'; this.value = undefined; this.fulfilledary = []; this.rejectedary = []; //=>执行excutor(异常捕获) let resolvefn = result => { let timer = settimeout(() => { cleartimeout(timer); if (this.status !== 'pending') return; this.status = 'fulfilled'; this.value = result; this.fulfilledary.foreach(item => item(this.value)); }, 0); }; let rejectfn = reason => { let timer = settimeout(() => { cleartimeout(timer); if (this.status !== 'pending') return; this.status = 'rejected'; this.value = reason; this.rejectedary.foreach(item => item(this.value)); }, 0); }; try { excutorcallback(resolvefn, rejectfn); } catch (err) { //=>有异常信息按照rejected状态处理 rejectfn(err); } } then(fulfilledcallback, rejectedcallback) { //=>处理不传递的状况 typeof fulfilledcallback !== 'function' ? fulfilledcallback = result => result : null; typeof rejectedcallback !== 'function' ? rejectedcallback = reason => { throw new error(reason instanceof error ? reason.message : reason); } : null; //=>返回一个新的promise实例 return new promise((resolve, reject) => { this.fulfilledary.push(() => { try { let x = fulfilledcallback(this.value); x instanceof promise ? x.then(resolve, reject) : resolve(x); } catch (err) { reject(err); } }); this.rejectedary.push(() => { try { let x = rejectedcallback(this.value); x instanceof promise ? x.then(resolve, reject) : resolve(x); } catch (err) { reject(err); } }); }); } catch(rejectedcallback) { return this.then(null, rejectedcallback); } static all(promiseary = []) {//=>promise.all() return new promise((resolve, reject) => { //=>index:记录成功的数量 result:记录成功的结果 let index = 0, result = []; for (let i = 0; i < promiseary.length; i++) { //=>promiseary[i]: //每一个需要处理的promise实例 promiseary[i].then(val => { index++; result[i] = val;//=>索引需要和promiseary对应上,保证结果的顺序和数组顺序一致 if (index === promiseary.length) { resolve(result); } }, reject); } }); } } module.exports = promise;
上一篇: 杏林同学录(七)
下一篇: 正则表达式匹配各种特殊字符