0

I wanted to make an array based on query results from mongodb, after created the array I can not print this outside of for loop here is the code

    let results = await model.find({status: 'active'});
    let finalResult = [];

     results.forEach( async result=> {
      let fromDate = new Date(result.validFrom);
      query = {
       createdAt: {
        $gte: fromDate.getTime(),
        $lte: toDate.getTime(),
       }
      }

       results1 = await model1.find(query);
         results1.forEach(result1=> {
          finalResult.push(result1);
        })
      
   });

   console.log(finalResult);

I am getting an empty array for finalResult log. can you please help me for this?

3
  • you missed the closing bracket of query object variable Commented May 29, 2021 at 12:03
  • Does this answer your question? How to return the response from an asynchronous call? Commented May 29, 2021 at 12:03
  • Use for...of and the question above to figure out how to return a value from an asynchronous call. Commented May 29, 2021 at 12:04

2 Answers 2

1

Use for...of instead of forEach. forEach recipes a callback function as a parameter, and it not support async function.

const results = await model.find({ status: 'active' });
const finalResult = [];

for (const result of results) {
  let fromDate = new Date(result.validFrom);
  query = {
     createdAt: {
        $gte: fromDate.getTime(),
        $lte: toDate.getTime(),
     }
  };
  const items = await model1.find(query);
  finalResult.push(...items);
}

console.log(finalResult);
Sign up to request clarification or add additional context in comments.

10 Comments

you not used the query variable, can you please use query variable as I used?
@mdkamrul Updated. But why?
because I have used this var at other place
how can I use results object at loop?
Do you mean results 's element? just change _ to what you want.
|
0

forEach with async doesn't work as expected. forEach don't wait for asynchronous calls. Better use map or for...of loops.

Using for...of is serial, Using map & Promise.all is parallel,

const results = await model.find({ status: 'active' });

const resultMap = results.map(async result =>  await model1.find({
    createdAt: {
      $gte: fromDate.getTime(),
      $lte: toDate.getTime(),
    }
  })
)

Promise.all(resultMap).then((data) => {
  console.log(data); // You might need one more loop here for finalData
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.