Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript wait for backend response while iterating array

I'm working with javascript and I want that wait for other function response before iterate next item.

Here is the desired behaviour:

enter image description here
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:

enter image description here

like image 223
Cesar Rodriguez Avatar asked Aug 04 '26 23:08

Cesar Rodriguez


1 Answers

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);
like image 189
CertainPerformance Avatar answered Aug 07 '26 13:08

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!