JavaScript ожидает ответа от бэкэнда во время итерации массива - PullRequest
0 голосов
/ 07 мая 2018

Я работаю с javascript и хочу, чтобы ожидание ответа другой функции перед повторением следующего элемента.

Вот желаемое поведение:

enter image description here
Это мой код:

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);

Это неверный результат:

enter image description here

Ответы [ 3 ]

0 голосов
/ 07 мая 2018

Может быть, это будет работать для вас

lista = [1, 2, 3, 4];

async function procesarItem(array, id) {
  if (id >= array.length) {
    console.log('Done');
    return;
  }
  console.log('-->START indice: ' + id);
  setTimeout(function () {
    console.log('-->FINISH indice: ' + id)
    procesarItem(array, id + 1);
  }, 2500);
  console.log('....waiting.... for : ' + id);
}

//Execute:
procesarItem(lista, 0);
0 голосов
/ 07 мая 2018

Вы также можете использовать обратный вызов:

let lista = [1,2,3,4]
console.log('Iteracion de la lista')
function procesarLista(array , callback){
  let isProcessDone = false;
  for(const item of array){

    //Simulate delay (for each iteration) of backend response
    setTimeout(function(){
            console.log('-->START indice: ' + item)
        console.log('....waiting.... for : ' + item );
        console.log('-->FINISH indice: ' + item)
        callback('Done')
    }, 2500);

  }
}
//Execute:
procesarLista(lista , function(result){
   // Do Something after each job is done
});

это будет вывод:

Iteracion de la lista
-->START indice: 1
 ....waiting.... for : 1
-->FINISH indice: 1
-->START indice: 2
 ....waiting.... for : 2
-->FINISH indice: 2
-->START indice: 3
 ....waiting.... for : 3
-->FINISH indice: 3
-->START indice: 4
 ....waiting.... for : 4
-->FINISH indice: 4

вот пример:

https://jsfiddle.net/op98bpka/1/

0 голосов
/ 07 мая 2018

Попробуйте await в Promise на каждой итерации внутри цикла for:

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 требуется время работы регенератора. Если у вас этого нет, тогда вы можете использовать reduce вместо этого, но вам придется await разрешение последней итерации внутри цикла и await окончательное обещание перед записью 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...