0

I want to loop on an array of ids and then get the variable by id and push to array.

      let variables = dVariables.map(async (idvariable) => {
        let variables = [];
        const v = await vModel.findById(idvariable);
        variables.push(v);
        console.log('variables_1:', variables);
        return variables;
      });

      console.log('variables///', variables);

In the terminal I receive as display:

variables_2: [{},{},{}]

variables_1: [
  {
    _id: 45e1aed1b5e9f5234ed520ce,
    name: 'name2',
    u: 'u2',
    v: 'v2',
    type: 't2',
    createdAt: 2021-06-07T23:03:56.092Z,
    updatedAt: 2021-06-07T23:03:56.092Z,
    __v: 0
  }
]

variables_1: [
  {
    _id: 55e1aed1b5d9f5135ed420ce,
    name: 'name1',
    u: 'u1',
    v: 'v1',
    type: 't1',
    createdAt: 2021-06-07T23:03:45.092Z,
    updatedAt: 2021-06-07T23:03:45.092Z,
    __v: 0
  }
]
Dev M
  • 1,519
  • 3
  • 29
  • 50
  • Have you wondered why `console.log` statement after the `map` method executes before any of the `console.log` statements inside the callback function of the `map()` method? – Yousaf Jun 08 '21 at 08:59
  • 1
    I would re-write your code as: `Promise.all(dVariables.map(idvariable => vModel.findById(idvariable))).then(resultArr => { /* code */ })` – Yousaf Jun 08 '21 at 09:01
  • @Yousaf **The map() is synchronous** this is why the console.log executes before any of the console.log statements inside the callback function of the map() method – Dev M Jun 08 '21 at 09:12
  • ...and before the asynchronous code returns results, `map()` has already executed, returning a promise in pending state in each iteration and that is what you see in the array assigned to `variables`. – Yousaf Jun 08 '21 at 09:15

0 Answers0