javascript - Wait for promise in a forEach loop - Stack Overflow

I am receiving a list of books from a database as a Promise.If the initial list of books is successfull

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 a utility function.

Inside the utility function is a forEach loop which loops over each initial book, makes an async call to get additional information, creates a new book object and adds it to an array of new books (called updatedBooks).

Problem: I don't know how to wait until the forEach loop is finished with every book and how to return the array of new books.

Currently, I only get one updated book instead of all

My ultimate goal is to have the list of updated books in the res.json() object

This is my current structure

controller.find(req.query)
    .then(function (entities) {
        awsUtil.addInfo(entities)
            .then(function (updatedBooks) {
                res.json({
                    confirmation: "success",
                    result: updatedBooks
                })
            })
            .catch(function (err) {
                res.json({
                    confirmation: "fail",
                    message: err
                })
            })
    })
    .catch(function (err) {
        res.json({
            confirmation: "fail",
            message: err
        })
    })

Function to get the initial books from MongoDB

find: function (params) {
    return new Promise(function (resolve, reject) {
        Book.find(params, function (err, books) {
            if (err) {
                reject(err)
                return
            }

            console.log("Org. Books List: ", books)
            resolve(books);
        })
    })
}

Utility function to get additional information and return a new array of books

addInfo: function (books) {
    return new Promise(function (resolve, reject) {
        let updatedBooks = [];

        books.forEach(function (book) {
            client.itemLookup({ //Call Amazon API to get book info
                idType: 'ISBN',
                itemId: book.isbn,
                responseGroup: 'ItemAttributes,Images'
            })
                .then(function (results) {
                    const updatedBook = {
                        // The additional info from result gets added here
                    }

                    updatedBooks.push(updatedBook);
                }).catch(function (err) {
                console.log(err);
                reject(err)
            });
        })
        resolve(updatedBooks) //Return the array of new books
    })
}

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 a utility function.

Inside the utility function is a forEach loop which loops over each initial book, makes an async call to get additional information, creates a new book object and adds it to an array of new books (called updatedBooks).

Problem: I don't know how to wait until the forEach loop is finished with every book and how to return the array of new books.

Currently, I only get one updated book instead of all

My ultimate goal is to have the list of updated books in the res.json() object

This is my current structure

controller.find(req.query)
    .then(function (entities) {
        awsUtil.addInfo(entities)
            .then(function (updatedBooks) {
                res.json({
                    confirmation: "success",
                    result: updatedBooks
                })
            })
            .catch(function (err) {
                res.json({
                    confirmation: "fail",
                    message: err
                })
            })
    })
    .catch(function (err) {
        res.json({
            confirmation: "fail",
            message: err
        })
    })

Function to get the initial books from MongoDB

find: function (params) {
    return new Promise(function (resolve, reject) {
        Book.find(params, function (err, books) {
            if (err) {
                reject(err)
                return
            }

            console.log("Org. Books List: ", books)
            resolve(books);
        })
    })
}

Utility function to get additional information and return a new array of books

addInfo: function (books) {
    return new Promise(function (resolve, reject) {
        let updatedBooks = [];

        books.forEach(function (book) {
            client.itemLookup({ //Call Amazon API to get book info
                idType: 'ISBN',
                itemId: book.isbn,
                responseGroup: 'ItemAttributes,Images'
            })
                .then(function (results) {
                    const updatedBook = {
                        // The additional info from result gets added here
                    }

                    updatedBooks.push(updatedBook);
                }).catch(function (err) {
                console.log(err);
                reject(err)
            });
        })
        resolve(updatedBooks) //Return the array of new books
    })
}
Share Improve this question asked Sep 3, 2017 at 19:43 JesterWestJesterWest 5092 gold badges5 silver badges14 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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"
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744853996a4597296.html

相关推荐

  • javascript - Wait for promise in a forEach loop - Stack Overflow

    I am receiving a list of books from a database as a Promise.If the initial list of books is successfull

    2天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信