我正在使用javascript,我希望在迭代下一项之前等待其他功能响应。
以下是所需行为:
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);
这是错误的结果:
答案 0 :(得分:1)
在await
循环内的每次迭代中尝试for
一个Promise:
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
需要regenerator-runtime。如果你没有,那么你可以改用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);
答案 1 :(得分:0)
也许这对你有用
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);
答案 2 :(得分:0)
你也可以使用回调:
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
这是一个例子: