0

NOTE: This is a Express.js app.

I have an array of users that I want to input into a DB:

const usersArray = //an array of user objects

And to input each user into the DB, I am using forEach to iterate over each object. But the issue is that there is a promise involved when inputting users into the DB, which will either return success (the user has been inserted into the DB), or return failure (for some reason, the user was not inserted into the DB).

The problem is that forEach doesn't actually wait to see how the promise resolves before iterating over the next object. How do I get forEach to wait for a promise to resolve before continuing?

The reason I want it structured this way: because once all the users have been inserted successfully into the DB, I want to be able to send a response to the front-end saying that, indeed, all the users have been inserted into the DB.

usersArray.forEach((user, index)=> {
    insertUserIntoDB(user).then(response => {
        console.log('User added to db!');
    }).catch(err => {
        console.log(err);
    });
    if (usersArray.length === index + 1) {
       /*This code should only execute once all the Users have been inserted into the DB*/
       res.send('success');
    }
    if (usersArray.length !== index + 1) {
        //At THIS point, I want forEach to resume
    }
});
MonkeyOnARock
  • 2,151
  • 7
  • 29
  • 53

0 Answers0