0

I am fetching userData from MongoDB by passing userId then awaiting for userData. Its returning userData if I request data without an array of ids. it gives me data. but if I run a loop on Array of ids and await that It gives me an array of promises but not an array of user data. why is that happening?.

I know how to solve it by await Promise.all(promiseArray).

but my question is why is this behavior? and also when I try to console the user in the map function it consoles userData, not the promise (on line 156). and I have learned that await stop the execution wait for the line that is awaiting to run then after that i continues. but here its not the case. its not stopping the map function instead if doesn't run code after the await but showing the behavior of continue keyword at await. and then after when the promise of await if fulfilled then code after that runs.

here is the code

// this.guides =  ["userIdOne","userIdTwo"]
tourSchema.post("save", async function (doc, next) {
  const guideSingle = await User.findById(this.guides[0]);

  const guideArray = this.guides.map(async (id) => {
    console.log("ID: ", id);
    let user = await User.findById(id);
    console.log("USER: ", user);
    return user;
  });

  console.log("SINGLE GUIDE: ", guideSingle);
  console.log("ARRAY GUIDE:", guideArray);
  next();
});

here I am adding output of this code. enter image description here

Mubasher Ali
  • 502
  • 6
  • 14
  • 1
    An `async` function always returns a Promise, even if you don't return one explicitly. In your example your return value is being wrapped within a Promise as your map callback is `async` – Nick Parsons Oct 03 '21 at 12:33
  • ok I understand, and also can you tell me about the consoling behavior? – Mubasher Ali Oct 03 '21 at 12:44
  • When the map callback is marked as async, it calls the callback function for each element without awaiting the callback, so it doesn't wait until the function is done for it moves to the next iteration - it instead calls the function, and then moves on without waiting for it to finish its full execution. – Nick Parsons Oct 03 '21 at 12:50
  • so you mean await here is cancelled out because map doesn't allow that? – Mubasher Ali Oct 03 '21 at 12:56
  • 2
    You can still use the syntax `async`/`await` syntax, the callback just isn't awaited before proceeding to the next iteration - it's the same behaviour with other methods like [forEach()](https://stackoverflow.com/q/37576685/5648954). You can compare behaviour of calling an async function and awaiting it vs calling it and not awaiting it in [this](https://jsfiddle.net/2pvrd1f8/) example – Nick Parsons Oct 03 '21 at 12:59

0 Answers0