等待多个并行操作如何更改以下代码,以便触发两个异步操作并使其有机会并发运行?const value1 = await getValue1Async();const value2 = await getValue2Async();// use both values我需要这样做吗?const p1 = getValue1Async();const p2 = getValue2Async();const value1 = await p1;const value2 = await p2;// use both values
3 回答
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
const [value1, value2] = await Promise.all([getValue1Async(),getValue2Async()]);
const promise1 = async() => {
return 3;}const promise2 = async() => {
return 42;}const promise3 = async() => {
return 500;
// emulate an error
// throw "something went wrong...";}const f1 = async() => {
try {
// returns an array of values
const results = await Promise.all([promise1(), promise2(), promise3()]);
console.log(results);
console.log(results[0]);
console.log(results[1]);
console.log(results[2]);
// assigns values to individual variables through 'array destructuring'
const [value1, value2, value3] = await Promise.all([promise1(), promise2(), promise3()]);
console.log(value1);
console.log(value2);
console.log(value3);
} catch (err) {
console.log("there was an error: " + err);
}}f1();
慕仙森
TA贡献1827条经验 获得超8个赞
使用.catch()和Promise.all()
unhandled rejectionPromise.all()
let myTimeout = (ms, is_ok) =>
new Promise((resolve, reject) =>
setTimeout(_=> is_ok ?
resolve(`ok in ${ms}`) :
reject(`error in ${ms}`),
ms));let handleRejection = promise => promise .then((...r) => [null, ...r])
.catch(e => [e]); (async _=> {
let res = await Promise.all([
myTimeout(100, true),
myTimeout(200, false),
myTimeout(300, true),
myTimeout(400, false)
].map(handleRejection));
console.log(res);})();let myTimeout = (ms, is_ok) =>
new Promise((resolve, reject) =>
setTimeout(_=> is_ok ?
resolve(`ok in ${ms}`) :
reject(`error in ${ms}`),
ms));let has_thrown = false;let handleRejection = promise => promise .then((...r) => [null, ...r])
.catch(e => {
if (has_thrown) {
console.log('not throwing', e);
} else {
has_thrown = 1;
throw e;
}
});(async _=> {
try {
let res = await Promise.all([
myTimeout(100, true),
myTimeout(200, false),
myTimeout(300, true),
myTimeout(400, false)
].map(handleRejection));
console.log(res);
} catch(e) {
console.log(e);
}
console.log('we are done');})();添加回答
举报
0/150
提交
取消
