I'm working with javascript and I want that wait for other function response before iterate next item.
Here is the desired behaviour:

This is my code:
let lista = [1,2,3,4]
console.log('Iteracion de la lista')
async function procesarLista(array){
for(const item of array){
console.log('-->START indice: ' + item)
//Simulate delay (for each iteration) of backend response
setTimeout(function(){
console.log('....waiting.... for : ' + item );
}, 2500);
console.log('-->FINISH indice: ' + item)
}
console.log('Done');
}
//Execute:
procesarLista(lista);
This is the WRONG result:

Try awaiting a Promise on each iteration inside the for loop:
let lista = [1, 2, 3, 4]
console.log('Iteracion de la lista')
async function procesarLista(array) {
for (const item of array) {
await new Promise((resolve) => {
console.log('-->START indice: ' + item)
//Simulate delay (for each iteration) of backend response
setTimeout(function() {
console.log('....waiting.... for : ' + item);
resolve();
}, 500);
});
console.log('-->FINISH indice: ' + item)
}
console.log('Done');
}
//Execute:
procesarLista(lista);
for..of requires regenerator-runtime. If you don't have that, then you can use reduce instead, but you'll have to await the last iteration's resolution inside the loop and await the final promise before logging Done:
let lista = [1, 2, 3, 4]
console.log('Iteracion de la lista')
async function procesarLista(array) {
await new Promise ((outerResolve) => {
array.reduce(async (lastPromise, item) => {
await lastPromise;
await new Promise((resolve) => {
console.log('-->START indice: ' + item)
//Simulate delay (for each iteration) of backend response
setTimeout(function() {
console.log('....waiting.... for : ' + item);
resolve();
}, 500);
});
console.log('-->FINISH indice: ' + item)
}, Promise.resolve());
});
console.log('Done');
}
procesarLista(lista);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With