友情链接
关于promise的介绍,请看此篇水文
本篇文章只是介绍实现promise以及promise常用方法。
正文
Promise使用
let promise = new Promise((resolve,reject)=>{resolve('success'); //这里如果是reject('fail')
});
promise.then((res)=>{console.log(res); // 输出:success
},(err)=>{console.log(err); // 上面如果执行reject('fail') 这里就输出:fail
});
实现
class Promise { //创建一个Promise类constructor(executor) {this.status = 'pending'; //初始默认状态为pendingthis.value = undefined; //默认赋值为undefinedthis.reason = undefined; //默认赋值为undefinedlet resolve = (value) => {if (this.status === 'pending') { //只有状态为pending才能转换状态this.value = value; //将传递进来的的值赋给value保存this.status = 'resolved'; //将状态设置成resolved}}let reject = (reason) => {if (this.status === 'pending') { //只有状态为pending才能转换状态this.reason = reason; //将传递进来的失败原因赋给reason保存this.status = 'rejected'; //将状态设置成rejected}}//默认执行executortry {executor(resolve, reject); } catch (e) {reject(e); //如果发生错误,将错误放入reject中}}then(onFulfilled, onRejected) { //等同于es5的Promise.prototype.then 当调用then的时候,根据状态,来执行不同的函数if (this.status === 'resolved') { //如果状态是resolvedonFulfilled(this.value); //执行成功的resolve,并将成功后的值传递过去}if (this.status === 'rejected') { //如果状态是rejectedonRejected(this.reason); //执行失败的reject,并将失败原因传递过去}}
}
module.exports = Promise; //将Promise导出
.all方法的实现
Promise.all = function (promiseArrs) { //在Promise类上添加一个all方法,接受一个传进来的promise数组return new Promise((resolve, reject) => { //返回一个新的Promiselet arr = []; //定义一个空数组存放结果let i = 0;function handleData(index, data) { //处理数据函数arr[index] = data;i++;if (i === promiseArrs.length) { //当i等于传递的数组的长度时 resolve(arr); //执行resolve,并将结果放入}}for (let i = 0; i < promiseArrs.length; i++) { //循环遍历数组promiseArrs[i].then((data) => {handleData(i, data); //将结果和索引传入handleData函数}, reject)}})
}
.race方法
race比赛竞赛的意思,也就是谁跑的快就返回谁,不管你是成功还是失败。跟all方法比较相似,但更简单一些。循坏之后直接
Promise.race = function (promises) {return new Promise((resolve, reject) => {for (let i = 0; i < promises.length; i++) {promises[i].then(resolve, reject);}})
}
.allSettle
如果任意的 promise reject,则 Promise.all 整个将会 reject。当我们需要 所有 结果都成功时,它对这种“全有或全无”的情况很有用:Promise.allSettled 等待所有的 promise 都被 settle,无论结果如何。结果数组具有:
- {status:“fulfilled”, value:result} 对于成功的响应,
- {status:“rejected”, reason:error} 对于 error。
Promise.allSettled = function (promises) {const rejectHandler = (reason) => ({ status: "rejected", reason });const resolveHandler = (value) => ({ status: "fulfilled", value });const convertedPromises = promises.map((p) =>Promise.resolve(p).then(resolveHandler, rejectHandler));return Promise.all(convertedPromises);
};