0
const allOrderStatus = ["afterPayment", "checkedOrder", "delayedDelivery"];

let dataCount = [];
allOrderStatus.map(async (item) => {
  const result = await this.model.countDocuments({
    orderStatus: item,
    sellerId: "5fe8d891bbefb5287c76e95c",
  });
  dataCount.push({ item: result });
});

console.log(dataCount);

If you use the for statement, it works fine, but if you use the map function, only the empty array exists in the dataCount. What's the reason?

vuongvu
  • 811
  • 6
  • 15
  • 1
    You might want to re-read what `.map()` does and how. – Andreas Mar 30 '21 at 06:59
  • 1
    `.forEach` instead `.map` – meine Mar 30 '21 at 06:59
  • 3
    Also relevant: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) and [Using async/await with a forEach loop](https://stackoverflow.com/q/37576685) – VLAZ Mar 30 '21 at 07:02
  • In your code, `allOrderStatus.map()` returns an array of [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)s that nobody [`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)s to settle. `console.log(dataCount);` does not print anything because the code that puts data in `dataCount` didn't run yet. You have to pass the return value of `allOrderStatus.map()` to [`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) and `await` the returned `Promise`. – axiac Mar 30 '21 at 07:11

0 Answers0