Skip to content
Advertisement

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 []

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement