等待多个并行操作

等待多个并行操作

如何更改以下代码,以便触发两个异步操作并使其有机会并发运行?


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


holdtom
浏览 395回答 3
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();

莫回无

使用.catch()和Promise.all()确保正确处理拒绝,并且可以安全地使用Promises.all()而不面临未处理的拒绝。(编辑:每次讨论澄清:不是错误unhandled rejection但是简单地说,拒绝是不被代码处理的。Promise.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);})();但是,您可以从CATCH()中抛出,以停止等待所有的结果(并丢弃其余的结果)-您可以每次尝试/捕获块只执行一次,因此需要维护和检查旗标SADS_SOWN,以确保不会发生未处理的错误。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');})();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript