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

200
Vistas
How to retain values of array inside async loop? javascript

I have code below that uses api to fetch customer data. Problem is when it the loop went to the second index, the customerIds does retain the value from the previous index (see console log below).

Somebody knows how to achieve this properly?


Here is my code

let customerIds = [];

arrayChunks.forEach(async (chunkGroupIds, index) => {
    try {
        console.log('customerIds - before', index, customerIds)

        const checkStatusResult = await checkStatus(
            token,
            chunkGroupIds
        )

        chunkGroupIds.map((customerId) => {
            const found = checkStatusResult.response.data.find(
                (data) => customerId.toString() === data.customerId
            )

            if (found) {
                customerIds = [...customerIds, customerId]
            }
        })
        
        console.log('customerIds - after', index, customerIds)
    } catch (error) {
        ...
    }
})

console.log('customerIds - final', customerIds)

Console logs: The problem can be shown by the text being printed. As we can see when it went to second index it did not get the previous value from index one.

customerIds - before 0 []
customerIds - after 0 [2,3,5]
customerIds - before 1 []
customerIds - after 1 []
... and so on

customerIds - final []
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Use for of loop instead of the callback approach

let customerIds = [];
let index = 0;

for (const chunkGroupIds of arrayChunks) {
    try {
        console.log('customerIds - before', index, customerIds)

        const checkStatusResult = await checkStatus(
            token,
            chunkGroupIds
        )

        chunkGroupIds.map((customerId) => {
            const found = checkStatusResult.response.data.find(
                (data) => customerId.toString() === data.customerId
            )

            if (found) {
                customerIds.push(customerId);
            }
        })
        
        console.log('customerIds - after', index, customerIds)
    } catch (error) {
        ...
    } finally {
       index++;
    }
}

console.log('customerIds - final', customerIds)
about 4 years ago · Juan Pablo Isaza Denunciar

0

This seems to be an asynchronism problem, it might seem as the promises in the array run sequentially, but they are not. In the forEach loop all of them are running simultaneously.

This might be something good in your case since you don't have to wait for the sum of the sequential time, where you probably are struggling is in the final part where you want to see the final array with all the appended values, for this I recommend the following:

const promises = arrayChunks.map(async (chunkGroupIds, index) => {
    try {
        console.log('customerIds - before', index, customerIds)

        const checkStatusResult = await checkStatus(
            token,
            chunkGroupIds
        )

        chunkGroupIds.map((customerId) => {
            const found = checkStatusResult.response.data.find(
                (data) => customerId.toString() === data.customerId
            )

            if (found) {
                customerIds = [...customerIds, customerId]
            }
        })
        
        console.log('customerIds - after', index, customerIds)
    } catch (error) {
        ...
    }
})

await Promise.all(promises); // Wait until all of them are finished
console.log('customerIds - final', customerIds)

Here the Promise.all utility allows you to wait until a collection of promises is finished, the functions are automatically mapped to a promise thanks to the async keyword.

In case you need your promises to be executed sequentially, you can use the approach recommended by @amir-saleem. Otherwise, my suggestion would be better in terms of performance.

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