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

94
Vistas
async / await / forEach function doesn't wait for response
async function updateJSON(original_JSON, assets_arr) {
  Object.keys(original_JSON).forEach(key => {original_JSON[key].active = false}); // reset all records
  Object.keys(assets_arr).forEach(async key => {
    let idx = original_JSON.findIndex(x => x.name === assets_arr[key].name);
    if (idx === -1) { // no match -> insert a new record
      const code_nr = await getCode(assets_arr[key].token_id);
      let debug = original_JSON.push({ name: assets_arr[key].name, active: true, code: code_nr });
      console.log("List len now:", debug);
    } else { original_JSON[idx].active = true; } // there is a match, so just update existing record to become 'active'
  });
  return original_JSON;
}

console.table(await updateJSON(original_JSON, assets_arr));

I cannot figure out a way for the code to wait for await getcode to finish before returning the function. I get a partial execution immediately and only then the code related to original_JSON.push is executed one record at the time.

If I remove async from line 3 and await from line 6 the function is executed sequentially(synchronously?), except then I get "Promise { }" instead of the code number the getCode function is supposed to retrieve. This number comes from a URL fetch().

I did read Async/Await not waiting and I think my problem is related. Do I need to use map() instead of forEach()? I find map() confusing. I do want to mutate the array, I'm not interested in making a new one (although I'll do it if that's what will fix this).

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

0

I got the solution from Nodejs forEach function doesn't wait for async functions: replacing the async forEach with a for loop fixes the problem. A while loop should work too. These fancy loop methods tripping people up when the simple ones do the job better!

async function updateJSON(original_JSON, assets_arr) {
  Object.keys(original_JSON).forEach(key => {original_JSON[key].active = false}); // reset all records
  for (const key in assets_arr) {
    let idx = original_JSON.findIndex(x => x.name === assets_arr[key].name);
    if (idx === -1) { // no match -> insert a new record
      const code_nr = await getCode(assets_arr[key].token_id);
      let debug = original_JSON.push({ name: assets_arr[key].name, active: true, code: code_nr });
      console.log("List len now:", debug);
    } else { original_JSON[idx].active = true; } // there is a match, so just update existing record to become 'active'
  };
  return original_JSON;
}

console.table(await updateJSON(original_JSON, assets_arr));
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