简体   繁体   English

编写嵌套的Promise JavaScript ES6

[英]Writing nested promise javascript es6

does anyone have any guides or tips on how to write a nested promises? 有没有人对如何编写嵌套的承诺有任何指导或技巧?

I am trying to turn the following nested for loop into a promise: 我正在尝试将以下嵌套的for loop转换为Promise:

let arr = [1, 2, 3, 4, 5]


for (i = 0; i < arr.length ; i++) {

  for (j = i + 1; j < arr.length ; j++) {

      // call another asynchronous function

  }

}

I thought about doing Promise.all , but the iterator in the inside for loop starts at j = i + 1 so I wasn't sure how to handle this with Promise.all . Promise.all打算做Promise.all ,但是for循环内部的迭代器从j = i + 1开始,所以我不确定如何用Promise.all处理它。

Thanks in advance! 提前致谢!

Push them into an array 将它们推入阵列

 let arr = [1, 2, 3, 4, 5] const promises = [] for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { promises.push(new Promise((resolve, reject) => { setTimeout(resolve, 100, [i,j]); })); } } Promise.all(promises).then(values => { console.log(values); }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM