Search code examples
javascriptloopbackjsarray.prototype.map

How to save with .push an array to read outside of .map(), with async?


I have an array named codigo and I .push it some data inside of .map(). When I put a console.log(codigo); inside the map() the result is correct, but when I put the console log outside of .map() the result is empty.

let pre = '';
let cod = [];
devPre.map(async (item)  => {
  pre = await models.pres.findOne({
    where: {
      id: item.pres_id,
    },
  });
  cod.push(pre.codPre);
  console.log(cod); // This return the correct values
});
console.log(cod); // This return [], this is my error

I need that the outside console.log returns with the correct values, like the other console.log.


Solution

  • Await a Promise.all over all values you're retrieving:

    const allPromises = devPre.map((item)  => {
      return models.pres.findOne({
        where: {
          id: item.pres_id,
        },
      });
    });
    const pres = await Promise.all(allPromises);
    const cod = pres.map(pre => pre.codPre);