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

193
Vistas
How can I run an asynchronous function inside a loop and get a return value (Node.js/Javascript)

I have a function containing a loop that iterates over an array of objects. On each iteration, I need to execute an asynchronous function and get a value back from the request however, I need each iteration of the for loop to pause and wait for the response before continuing.

For example:

const tokeniseCustomer = async () => {
const object [{"val1":1,"val2":2},{"val1":"a","val2":"b"}];
for (let index = 0; index < object.length; index += 1) {
const data = await getData(object[index]);
console.log(data);
//wait for data before progressing to next loop iteration
}
};

I thought by adding the "await" keyword in the above example, the loop would wait for the getData function to return a value.

The problem with the above code is that nothing gets logged to the console. I tried troubleshooting this by adding some extra logging. For example:

const tokeniseCustomer = async () => {
const object [{"val1":1,"val2":2},{"val1":"a","val2":"b"}];
for (let index = 0; index < object.length; index += 1) {
console.log('a')
const data = await getData(object[index]);
console.log('b');
console.log(data);
//wait for data before progressing to next loop iteration
}
};

The above code logs 'a' but not 'b'.

This is what my getData function looks like:

const getData = async (object) => {
  //get the data from MSSQL and return it
  const result = await MSSQLFUNCTION(object);
  return result;
};

I am really not sure what I am doing wrong. Am I incorrect in using for loops with await?

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

0

Await can only be used inside an async function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#:~:text=It%20can%20only%20be%20used%20inside%C2%A0an%20async%20function

function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
const object = [
  { val1: 1, val2: 2 },
  { val1: "a", val2: "b" },
];
(async () => {
  for (let index = 0; index < object.length; index += 1) {
    console.log("a");
    const data = await sleep(5000)
    console.log("b");
    console.log(data);
  }
})();

about 4 years ago · Juan Pablo Isaza Denunciar

0

Can you try the snippet mentioned below: This basically runs a reducer over the array and waits for previous promise to complete before executing next one

const tokeniseCustomer = async () => {
  const object = [{"val1":1,"val2":2},{"val1":"a","val2":"b"}];
  object.reduce(async (acc, curr) => {
    await acc;
    return getData(curr);
  }, Promise.resolve(null))
 }
   
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