簡體   English   中英

如何使 for 循環等待所有異步函數完成。 異步函數里面有多個異步函數

[英]How to make for loop wait for all async functions to finish. async functions has multiple async functions inside in it

我有一個數組,例如 [1,2,3,4,5,6,7,8,10]。

我喜歡一次處理一個項目。 同步。

我也混合了非異步函數。

var array = [1,2,3,4,5,6,7,8,9,10]
for(i=0; i< array.length; i++){
    var result = await fun1(array[i]);
    console(result) //expecting print out 2,4,6,8,10...20 synchronously
}

async function fun1(item){
    return fun2(item);
}
async function fun2(item){
    a = new A(item)
    return a.hello()
}

class A{
    constructor(item){
       this.item = item;
    }

    hello(){
        //do something
        return this.item * 2;
    }
}

如何在 Node.JS 中實現它?

您可以使用 Promise.all 功能。

const promises = [];
const array = [1,2,3,4,5,6,7,8,9,10]
array.forEach((num)=>{
  promises.push(func1(num))
});

Promise.all(promises)
.then(response => console.log(response)); // your required response

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM