当前位置:网站首页>36 - 新的 Promise 方法:allSettled & any & race
36 - 新的 Promise 方法:allSettled & any & race
2022-07-27 05:42:00 【前端码农小王】
简介
在之前的两篇文章中,我们已经覆盖了基础和高级的 promise 知识。还有两个不错的新操作符/方法,可以是代码更简洁,让我们一起来重温下它们。
allSettled
ES2020 或 ES11 引入了 promise.allSettled,所以它是很新的方法所以使用的时候需要当心。使用之前需要确定你要支持的浏览器版本。
当所有的 promise 返回不管是成功还是失败,allSettled 都会返回一个 promise。返回值是一个对象数组,其中每一项描述了输入 promise 的返回值。
allSettled 和 all 有一些区别。
all 会返回输入的 promise 中第一个是失败的结果,所以如果我们输入了 5 个 promise 其中两个失败了,all 会返回第一个失败的结果。
allSettled 则会等待所有的 promise 完成然后返回所有按输入顺序对应的结果。当异步的任务彼此没有依赖关系使用 allSettled 然后重试失败的任务。若你的执行步骤依赖所有的异步任务则使用 all。
const promise1 = Promise.resolve("Parwinder");
const promise2 = new Promise((resolve) => {setTimeout(() => {resolve("Lauren");}, 2000);
});
const promise3 = Promise.reject("Robert");
const promise4 = Promise.resolve("Eliu");
Promise.allSettled([promise1, promise2, promise3, promise4]).then((data) => {console.log(data);
});
上面四个任务一旦都结束(成功或失败),allSettled 则会向 then 的回调函数中传递结果,打印如下:
[{status: "fulfilled",value: "Parwinder"
}, {status: "fulfilled",value: "Lauren"
}, {reason: "Robert",status: "rejected"
}, {status: "fulfilled",value: "Eliu"
}]
any
any 的输入参数一般是可迭代对象比如数组,它返回数组中第一个成功 promise 的结果,若所有的 promise 都失败则返回 AggregateError ,AggregateError 是用来组合输入 promise 返回的独立错误。
any 与 all 是相对的。
const promise1 = Promise.resolve("Parwinder");
const promise2 = new Promise((resolve) => {setTimeout(() => {resolve("Lauren");}, 2000);
});
const promise3 = Promise.reject("Robert");
const promise4 = Promise.resolve("Eliu");
Promise.any([promise1, promise2, promise3, promise4]).then((data) => {console.log(data); // Parwinder (first successful promise)
});
假设所有的 promise 都返回错误:
const promise1 = Promise.reject("Parwinder");
const promise2 = new Promise((resolve,reject) => {setTimeout(() => {reject("Lauren");}, 2000);
});
const promise3 = Promise.reject("Robert");
const promise4 = Promise.reject("Eliu");
Promise.any([promise1, promise2, promise3, promise4]).then((data) => {console.log(data); // "AggregateError: No Promise in Promise.any was resolved"
});
race
race 会返回第一个成功或失败 promise 的结果。
const promise1 = new Promise((resolve, reject) => {setTimeout(resolve, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {setTimeout(resolve, 100, 'two');
});
Promise.race([promise1, promise2]).then((value) => {console.log(value);// Both resolve, but promise2 is faster
});
// expected output: "two"
若传递给 race 的参数为空数组,则永远不会有结果:
var foreverPendingPromise = Promise.race([]);
console.log(foreverPendingPromise);
setTimeout(function(){console.log('the stack is now empty');console.log(foreverPendingPromise);
});
// logs, in order:
// Promise { <state>: "pending" }
// the stack is now empty
// Promise { <state>: "pending" }
边栏推荐
- regular expression
- Customer cases | focus on process experience to help bank enterprise app iteration
- R2live code learning record (3): radar feature extraction
- MySQL的基本语句(1)—增删改查
- ZnS-DNA QDs近红外硫化锌ZnS量子点改性脱氧核糖核酸DNA|DNA修饰ZnS量子点
- Summary of APP launch in vivo application market
- 【Latex格式】双栏双图左右并排有小标题、上下并列有小标题
- 最新!国资委发布国有企业数字化转型新举措
- Brief introduction of simulation model
- Analysis on the current situation and optimization strategy of customer experience management in banking industry
猜你喜欢

Two ways of multi GPU training of pytorch

Auto encoder (AE), denoising auto encoder (DAE), variable auto encoder (VAE) differences

Express receive request parameters

关于卡尔曼滤波的协方差如何影响deepsort的跟踪效果的考虑

New features of ES6 (2)

Hospital reservation management system based on SSM

CdS quantum dots modified DNA | CDs DNA QDs | near infrared CdS quantum dots coupled DNA specification information

Gbase 8C product introduction

O2O电商线上线下一体化模式分析

How to learn C language? This article gives you the complete answer
随机推荐
[latex format] there are subtitles side by side on the left and right of double columns and double pictures, and subtitles are side by side up and down
客户案例 | 聚焦流程体验,助银行企业APP迭代
银行业客户体验管理现状与优化策略分析
VIVO应用市场APP上架总结
What is the reason why dragging the timeline is invalid when playing device videos on the easycvr platform?
DNA(脱氧核糖核酸)供应|碳纳米管载核酸-DNA/RNA材料|DNA/RNA核酸修饰磁性纳米颗粒
Dsgan degenerate network
强网杯2021 pwn 赛题解析——babypwn
Datascience: data generation adds a small amount of noise (customizable noise) to the original data to realize the construction of new data (dataframe format data storage case)
Talk about multimodality of fire
Using docker to install and deploy redis on CentOS
ZnS DNA QDs near infrared zinc sulfide ZnS quantum dots modified deoxyribonucleic acid dna|dna modified ZnS quantum dots
【Latex格式】双栏双图左右并排有小标题、上下并列有小标题
deepsort源码解读(一)
jest单测样式问题【identity-obj-proxy】npm包
含有偶氮苯单体的肽核酸寡聚体(NH2-TNT4,N-PNAs)齐岳生物定制
Neural network parameter initialization
EasyCVR设备管理列表页面搜索时,分页数据不显示的问题修复
DNA modified near infrared two region GaAs quantum dots | GaAs DNA QDs | DNA modified GaAs quantum dots
NAT (network address translation)