Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

419
Vistas
How can I push elements out of a forEach() context?

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 !

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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() { ... )

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda