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

137
Vistas
Trouble understanding the flow of this Promise chain
async function chicks(nest, year) {
  let list = "";
  await Promise.all(network(nest).map(async name => {
    list += `${name}: ${
      await anyStorage(nest, name, `chicks in ${year}`)
    }\n`;
  }));
  return list;
}

This function is supposed to return a list of all the nests in a network along with the number of chicks that hatched in them during the year. Network(nest)returns an array with the name of all the nests in the network, while anyStorage will return the # of chicks hatched at a given nest as a Promise.

What I don't understand is some of the things pointed out in the textbook.

The code is seriously broken. It’ll always return only a single line of output, listing the nest that was slowest to respond.

Can you work out why?

The problem lies in the +=operator, which takes the current value of list at the time where the statement starts executing and then, when the await finishes, sets the list binding to be that value plus the added string.

But between the time where the statement starts executing and the time where it finishes there’s an asynchronous gap. The map expression runs before anything has been added to the list, so each of the += operators starts from an empty string and ends up, when its storage retrieval finishes, setting list to a single-line list—the result of adding its line to the empty string.

I am not quite sure why only one line is getting recorded to list, once map goes through the first item in the array, why does list not get updated?

And why is the only line to be recorded the slowest nest to respond? Since there is an await in front of anyStorage? Should it not be the last item in the array that is recorded since the function freezes until the promise is resolved?

I am confused as to how Promise all works when the promises inside the array contain other promises. The way i see it Promise.all holds an array of promises( from map) that contain promises from anyStorage. Promise.all is supposed to show an array of the promise values if they all resolved. This works also if the promises inside the promise are resolved also???

Thanks for any help provided.

about 4 years ago · Juan Pablo Isaza
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