0
let connectionIDs = [];
_.each(connections, async connection => {
    let id = connection.id;
    let connector = await UserProfile.findOne({phoneNumber: id});
    connectionIDs.push({
        name: connector.name.split(" ")[0],
        imageID: connector.imageID,
        phoneNumber: connector.phoneNumber
    })
});
console.log(connectionIDs) //// []

It always returns empty connectionIDs. ie. It does not wait for loop to finish.

What am I missing, I tried appending await with loop i.e await _.each(... and tried wrapping the loop inside Promise.all(.. But I think I am not clear with basics and I hope I can clear the concepts much with this example.

Zafta
  • 655
  • 1
  • 10
  • 26

2 Answers2

1

You can do something like this:

const connectionIds = await Promise.all(connections.map(async connection => {
    let id = connection.id;
    let connector = await UserProfile.findOne({phoneNumber: id});
    return {
        name: connector.name.split(" ")[0],
        imageID: connector.imageID,
        phoneNumber: connector.phoneNumber
    }
}))

Basically, you can map the existing array to an array of promises that will allow Promise.all to do it's job.

nvitaterna
  • 416
  • 5
  • 12
0

I solved the problem by omitting the use of lodash function and replacing it with a simple for..of method.

But I am not able to understand why it works. One of the member wrote a comment to the post where the solution was given. (ie here Using async/await with a forEach loop)

enter image description here

Zafta
  • 655
  • 1
  • 10
  • 26