How to return many Promises and wait for them all before doing other stuff

后端 未结 5 1926
北荒
北荒 2020-11-21 23:02

I have a loop which calls a method that does stuff asynchronously. This loop can call the method many times. After this loop, I have another loop that needs to be executed o

5条回答
  •  滥情空心
    2020-11-21 23:15

    const doSomeAsyncStuff = async (funcs) => {
      const allPromises = funcs.map(func => func());
      return await Promise.all(allPromises);
    }
    
    doSomeAsyncStuff([
      () => new Promise(resolve => setTimeout(() => resolve(), 100)),
      () => new Promise(resolve => setTimeout(() => resolve(), 100)),
      () => new Promise(resolve => setTimeout(() => resolve(), 100)),
      () => new Promise(resolve => setTimeout(() => resolve(), 100)),
      () => new Promise(resolve => setTimeout(() => resolve(), 100)),
    ]);
    

提交回复
热议问题