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

后端 未结 5 1787
北荒
北荒 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:30

    A reusable function works nicely for this pattern:

    function awaitAll(count, asyncFn) {
      const promises = [];
    
      for (i = 0; i < count; ++i) {
        promises.push(asyncFn());
      }
    
      return Promise.all(promises);
    }
    

    OP example:

    awaitAll(5, doSomeAsyncStuff)
      .then(results => console.log('doSomeStuffOnlyWhenTheAsyncStuffIsFinished', results))
      .catch(e => console.error(e));
    

    A related pattern, is iterating over an array and performing an async operation on each item:

    function awaitAll(list, asyncFn) {
      const promises = [];
    
      list.forEach(x => {
        promises.push(asyncFn(x));
      });
    
      return Promise.all(promises);
    }
    

    Example:

    const books = [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }];
    
    function doSomeAsyncStuffWith(book) {
      return Promise.resolve(book.name);
    }
    
    awaitAll(books, doSomeAsyncStuffWith)
      .then(results => console.log('doSomeStuffOnlyWhenTheAsyncStuffIsFinished', results))
      .catch(e => console.error(e));
    

提交回复
热议问题