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?

mdkamrul
  • 274
  • 1
  • 13
  • you missed the closing bracket of `query` object variable – turivishal May 29 '21 at 12:03
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – goto May 29 '21 at 12:03
  • Use `for...of` and the question above to figure out how to return a value from an asynchronous call. – goto May 29 '21 at 12:04

2 Answers2

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);
hoangdv
  • 15,138
  • 4
  • 27
  • 48
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
})
Naren
  • 4,152
  • 3
  • 17
  • 28