当前位置:网站首页>36 - new promise method: allsettled & any & race
36 - new promise method: allsettled & any & race
2022-07-27 07:16:00 【Front end code: Nong Xiaowang】
brief introduction
In the previous two articles , We have covered basic and advanced promise knowledge . There are also two nice new operators / Method , It can be that the code is simpler , Let's review them .
allSettled
ES2020 or ES11 Introduced promise.allSettled, So it is a very new method, so you need to be careful when using it . Before using, you need to determine the browser version you want to support .
When all promise Return whether success or failure ,allSettled Will return to one promise. The return value is an array of objects , Each of these describes the input promise The return value of .
allSettled and all There are some differences .
all Will return the entered promise The first is the result of failure , So if we enter 5 individual promise Two of them failed ,all Will return the first failed result .
allSettled Will wait for all promise Complete and return all the results corresponding to the input order . When asynchronous tasks have no dependencies on each other, use allSettled Then retry the failed task . Use if your execution steps depend on all asynchronous tasks 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);
});
Once the above four tasks are completed ( Success or failure ),allSettled Will go to then The result is passed in the callback function of , Print as follows :
[{status: "fulfilled",value: "Parwinder"
}, {status: "fulfilled",value: "Lauren"
}, {reason: "Robert",status: "rejected"
}, {status: "fulfilled",value: "Eliu"
}]
any
any The input parameters of are usually iteratable objects such as arrays , It returns the first success in the array promise Result , If all promise If both fail, it returns AggregateError ,AggregateError Is used to combine input promise Independent error returned .
any And all Is relative .
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)
});
Suppose that all promise All return errors :
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 Will return the first success or failure promise Result .
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"
If passed to race The parameter of is an empty array , There will never be a result :
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" }
边栏推荐
- 把Excel转换成CSV/CSV UTF-8
- 大疆livox定制的格式CustomMsg格式转换pointcloud2
- Interpretation of deepsort source code (VII)
- Automatically generate UML sequence diagram according to text (draw.io format)
- Knowledge points and answers of PHP intermediate interview in 2020
- Music website management system based on SSM
- VScode连接远程服务器开发
- 用typescript实现排序-递增
- VIVO应用市场APP上架总结
- Vscode connection remote server development
猜你喜欢

Jmeter:接口自动化测试-BeanShell对数据库数据和返回数据比较

Reflection on pytorch back propagation

DDD Domain Driven Design Notes

How MySQL executes query statements

基于SSM实现的校园新闻发布管理系统

(转帖)eureka、consul、nacos的对比2

Summary of APP launch in vivo application market

Drools(5):Drools高级语法

Instruction set x digital technology accelerates the digital transformation of government and enterprises, and builds Unicorn enterprise alliance in DT field

Watermelon book learning Chapter 5 --- neural network
随机推荐
Analysis of strong tennis cup 2021 PWN competition -- babypwn
adb指令整理
Drools(5):Drools高级语法
Consideration on how the covariance of Kalman filter affects the tracking effect of deepsort
AI: play games in your spare time - earn it a small goal - [Alibaba security × ICDM 2022] large scale e-commerce map of risk commodity inspection competition
A Competitive Swarm Optimizer for Large Scale Optimization
LogCat工具
C#时间相关操作
美联储SR 11-7:模型风险管理指南(Guidance on Model Risk Management)-万字收藏
Vscode connection remote server development
MySQL index failure and solution practice
指令集 x 数澜科技丨加速政企数字化转型,打造DT领域独角兽企业联盟
Dajiang livox customized format custommsg format conversion pointcloud2
pre-commit install 时 CalledProcessError
Campus news release management system based on SSM
【Latex格式】双栏双图左右并排有小标题、上下并列有小标题
2021 interview questions for php+go of Zhongda factory (2)
How does golang assign values to empty structures
36 - 新的 Promise 方法:allSettled & any & race
Go obtains the processing results of goroutine through channel