Wait for promise in a forEach loop

后端 未结 1 1376
有刺的猬
有刺的猬 2021-01-18 09:02

I am receiving a list of books from a database as a Promise.

If the initial list of books is successfully loaded, the books are further processed by passing them to

相关标签:
1条回答
  • 2021-01-18 09:11

    Modify the addInfo method so it stores the promises in an array, and return Promise.all instead, which will resolve when all the promises have resolved.

    Assuming your methods returns a promise, and it looks like they do, something like

    addInfo: function(books) {
      let promises = books.map(function(book) {
        return client.itemLookup({
          idType        : 'ISBN',
          itemId        : book.isbn,
          responseGroup : 'ItemAttributes,Images'
        }).then(function(results) {
          return {
            // The additional info from result gets added here
          }
        });
      })
      return Promise.all(promises); // catch errors where you call "addInfo"
    }
    
    0 讨论(0)
提交回复
热议问题