anita shrivastava
anita shrivastava

Reputation: 329

How to write a non-blocking for loop in node js

I have two collections in mongoose db. I have to find all the documents in a collection. After that, i have to iterate all the documents to find the corresponding document in second collection. For that, i was thinking to use for loop. But, since it is blocking in nature. How can I perform my task.

const docs = await collection1.find({name:"asdf"})
for(let i=0;i<docs.length;i++){
    const doc2 = await collection2.findOne({address:docs.address})
}

Upvotes: 0

Views: 429

Answers (1)

Filipe Doutel Silva
Filipe Doutel Silva

Reputation: 139

I'm not sure if I really understand your problem, but if I do, I think you can push all yours promises inside an array, instead of using await. After that you can use the function Promise.all to await in on place for all promises inside the array. You can find below an example with your code:

const docs = await collection1.find({name:"asdf"})
const docs2 = [];
for(let i=0;i<docs.length;i++){
    docs2.push(collection2.findOne({address:docs.address}));
}

Promise.all(docs2).then((values) => {
  // at this point all your documents are ready
  // and your for is not blocking
  console.log(values);
});

But you have to be carefull to not abuse of this, if you fill an array with a lot of promises, it can lead to performance/memory issues. Regards

Upvotes: 2

Related Questions