【问题标题】:How to make for loop wait for all async functions to finish. async functions has multiple async functions inside in it如何使 for 循环等待所有异步函数完成。异步函数里面有多个异步函数
【发布时间】:2020-09-07 15:38:38
【问题描述】:

我有一个数组,例如 [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 中实现它?

【问题讨论】:

    标签: javascript node.js asynchronous async-await synchronization


    【解决方案1】:

    您可以使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-29
      • 2019-07-02
      • 1970-01-01
      • 2019-06-16
      相关资源
      最近更新 更多