1

This is my first post ever :)

So what I am trying to do is loop through keys of an object with a forEach() loop and for each element, push specific values into an array. Then after the loop, resolve the array containing all pushed values.

As I understand, it's hard to get out values of the forEach() context. Is there a way to do something like that ?

Here's a code exemple of what I'm trying to do:

    some function returning a promise
    ... 
    ...

    let promisesArray = [];

    //Loop on each object from data and do whatever
    ObjectJSON.array.forEach((object) => {
      if (object.key === "foo") {
        functionBar()
          .then((response) => {
            promisesArray.push(
              `Object: ${object.key}  |  ${object.someOtherKey}`
            );
          })
          .catch((error) => {
            reject(error);
          });
      }
    });

    resolve(promisesArray);

  }); //end of promise's return

Right now, it returns an empty array.

The expected result should be something like this instead:

[
  'Object: key1  |  someOtherKey1',
  'Object: key2  |  someOtherKey2',
  'Object: key3  |  someOtherKey3',
  ...
]

Thanks a lot for your answers !

matreurai
  • 147
  • 12
  • pls provide reproducible example – captain-yossarian from Ukraine Jan 14 '22 at 13:36
  • 1
    This reeks of the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it). And no, [you cannot use `forEach` for an asynchronous loop](https://stackoverflow.com/a/37576787/1048572). – Bergi Jan 14 '22 at 13:41
  • 1
    I would strongly suggest you read through the [`javascript.info/async`](https://javascript.info/async) chapter. It will walk you through the core principles of working with asynchronous operations in javascript. – Olian04 Jan 14 '22 at 14:31

1 Answers1

1

Congrats on your first post ever!

It's a super classic question though, how to use an asynchronous function in a loop. With .forEach you can't, but you can using await in a for loop :

let promisesArray = [];

for (let object of ObjectJSON.array) {
  if (object.key !== "foo") continue;

  const response = await functionBar();

  promisesArray.push(
    `Object: ${object.key}  |  ${object.someOtherKey}`
  );
}

resolve(promisesArray);

Using await will probably require your function to be marked as async (async function doSomething() { ... )

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63