Naco
Naco

Reputation: 33

Asynchronous code inside an for each loop

This is my first post, because I usually find a way to answer my questions via the old messages... But this time I'm stuck. I hope you can help me.

searchUser.forEach(function(item, i) {
        getUser(item)
        .then(objUser => {
            console.log(i);
            console.log(objUser);
            name = objUser.name;
            let idConversation = objUser.id;
            createNewConversation(name, idConversation)
        })
    })

My getUser is an asynch function, and I don't know why, but it seems that my construction does not work. it only creates the number of conversations i have but with the content of the last conversation and not the others... any idea of what I'm missing there? by the way console.log(i) gives 1 and then 0.

FYI the getUser is a function that returns data from the user.

Upvotes: 3

Views: 46

Answers (1)

Taki
Taki

Reputation: 17654

Having an async function inside a forEach loop can be tricky to debug, i would suggest using Promise.all to call createNewConversation after all of the promises are resolved :

const promises = searchUser.map(item => getUser(item));

Promise.all(promises).then(result => {
  result.forEach(({ name, id }) => {
    createNewConversation(name, id);
  });
});

Upvotes: 4

Related Questions