Push array only works inside callback

Asked

Viewed 85 times

0

I am trying to update an array with values returned by Mongoose. But the array returns empty. It follows the code snippet:

let y = [];
Vendas.countDocuments(
  { dt_encerramento: { $gte: jan, $lte: abr }},
    function(err, os) {
      y.push(os);
    }
  );

Give up console.log(y) inside the callback, I have the values. I run right after the countDocuments, returns an empty array.

Would anyone know what I’m doing wrong?

1 answer

0

This happens because of problems with the asynchronous character of the callback. In this case, you should use Names together with async/await:

async countDoucments() {
   const numeroDeDocumentos = await Vendas.count({ dt_encerramento: { $gte: jan, $lte: abr }}).exec();
   return numeroDeDocumentos;
}

Thus, when calling the asynchronous function countDocuments, you will receive a file containing the number of documents.

  • I appreciate the answer João, but I still haven’t been able to take the value of the variable and move to the array. I tried several ways, follow one of them: async function docs() {
 const numDocs = await Vendas.countDocuments({ dt_encerramento: { $gte: jan, $lte: abr }}).exec();
 return numDocs;
 }
 docs().then(function (err,n) {
 y.push(n);
 });


  • You need to understand the difference between asynchronous work and synchronous work. In this case for example, within another async function, you can do: y.push(await countDocuments())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.