首页 > 其他 > 详细

await Promise.all([ ]) VS mutiple await

时间:2019-11-12 14:24:37      阅读:90      评论:0      收藏:0      [点我收藏+]

应用场景:有多个异步的方法,需要同步化序列,这时候一般的处理是定义一个方法,利用 async 将其 一个一个添加 await 然后执行,也可以利用 Promise.all 来处理,相比之下,使用 Promise.all([ ]) 的方法,可以更加高效的执行,能够快速的去序列化,但是使用这个方法的劣势就是,一旦有异常了 promise 就会跳出,进而进行 catch 的回调,这样异常之后 promise.all 里边的代码语句就不会执行了;例如:

async function test () {
  console.log( new Date().getSeconds(),‘a‘); 
  await rej(1000); 
  await rej(2000);
  await rej(3000);
  console.log( new Date().getSeconds(),‘b‘);
};
async function test1 () {
  console.log( new Date().getSeconds(),‘c‘); 
  await Promise.all([rej(1000), rej1(2000), rej2(3000)]);
  console.log( new Date().getSeconds(),‘d‘);
};
var rej = (time) => new Promise((resolve, reject) => {
      setTimeout(() => resolve(‘reject‘), time);
 }); 
var rej1 = (time) => new Promise((resolve, reject) => {
      setTimeout(() => reject(‘reject‘), time);
 }); 
var rej2 = (time) => new Promise((resolve, reject) => {
      setTimeout(() => resolve(‘reject‘), time);
 }); 
test();
test1();

  

 

await Promise.all([ ]) VS mutiple await

原文:https://www.cnblogs.com/mufc/p/11841369.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!