0

I have an function for each await and it gives a string and adds it to an array, but the log that I got later shows the array is empty and it is done before the for each is done.

 const paths: Array<string> = [];
  await filterFiles.forEach((data, index) => {
    fileSave(data, `${name}@${index}`, National_Code, "medium", "image")
      .then((data: string) => {
        paths.push(data);
        console.log(paths);
        console.log("log 2");
      })
      .catch((err) => {
        res.status(500).json("There is a problem saving the files");
        return err;
      });
  });
  console.log(paths);
  console.log("log 1");

Result :

[]
log 1
[ 'image/Czech@0_0927735016.jpeg' ]
log 2
[ 'image/Czech@0_0927735016.jpeg', 'image/Czech@1_0927735016.jpeg' ]
log 2

What did I do wrong?

  • Also probably relevant: [Using async/await with a forEach loop](https://stackoverflow.com/q/37576685) – VLAZ Dec 16 '21 at 19:13
  • Array.forEach is not an async function. It's technically possible to put the await keyword in front of any function, but if the function isn't async then the await is not doing anything. It behaves the same as if you would call the function without await. – The Fool Dec 16 '21 at 20:36

0 Answers0