1

My code is:

      if (!finalLicenses == []) {
        productsOwnedString = finalLicenses.join("\n");
      }
licenses.forEach(async (license) => {
        const product = await Product.findOne({ _id: license.product }).exec();
        console.log("New Product: " + product.name);
        if (product) finalLicenses.push(product.name);
});
      if (!finalLicenses == []) {
        productsOwnedString = finalLicenses.join("\n");
      }
      print(finalLicenses)

however

      if (!finalLicenses == []) {
        productsOwnedString = finalLicenses.join("\n");
      }
      print(finalLicenses)

is running before

licenses.forEach(async (license) => {
        const product = await Product.findOne({ _id: license.product }).exec();
        console.log("New Product: " + product.name);
        if (product) finalLicenses.push(product.name);
});

is done. I know this because My logs look like this:

[] // the finalLicenses log
New Product: test // the New Product log in the forEach

Does anyone know how I can fix this issue? I tried adding await before finalLicenses.join but that didn’t help.

donzee529
  • 49
  • 2
  • 1
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – crashmstr Jul 28 '22 at 18:01
  • `forEach` dies not Support async callbacks. Use a `for .. of` loop instead – derpirscher Jul 28 '22 at 18:02

0 Answers0