-1

This is the code snippet. I want to access imagePath array inside for each.

...

const imagePath=[];
             
req.files.images.forEach(async (image) => {
   let extName = path.extname(image.name);
   var dest = path.join(__dirname, '..', 'public', 'images', 'items');
   var imgPath = await saveFile(image, dest, itemName, extName);
   imagePath.push(imgPath); // this line
})

...

Vishal Rathore
  • 83
  • 1
  • 1
  • 5
  • yes, that's how you do it - of course, there's no guarantee the order will be maintained since you have asynchronous code inside the forEach – Jaromanda X Nov 13 '20 at 05:19
  • it's not working – Vishal Rathore Nov 13 '20 at 05:20
  • 1
    "it's not working" is not useful ... what is happening that is different to what you expect? your code will "work" as is, no errors in the code itself .... so ... what's the *actual* problem? - let me guess, on the very next line, you `console.log(imagePath)` and it's empty? That would be due to asynchrony inside the forEach callback – Jaromanda X Nov 13 '20 at 05:21
  • Yes, you are correct. I checked other vaiable. I can access them. – Vishal Rathore Nov 13 '20 at 05:22
  • see, you should present the code you have an issue with :p – Jaromanda X Nov 13 '20 at 05:23
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+async+push+in+foreach+array+empty) of [Array keep empty after push object from forEach](https://stackoverflow.com/q/62274923/4642212). – Sebastian Simon Nov 13 '20 at 05:35

1 Answers1

-2

Normally, imagePath is easily accessible in your forEach loop.

However, your forEach callback is asynchronous. If you do a console.log(imagePath) right after the forEach loop, you will get an empty array.

A simple workaround would be to use a forin loop.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Aaron_Actu
  • 112
  • 8
  • 1
    This answer doesn’t explain how a `for`…`in` loop helps with asynchronicity at all. You can step in the same traps as with the `forEach` call, and you can make the code work without `for`…`in`. – Sebastian Simon Nov 13 '20 at 05:33