gpt4 book ai didi

JavaScript 在迭代数组时等待后端响应

转载 作者:行者123 更新时间:2023-11-29 23:22:22 25 4
gpt4 key购买 nike

我正在使用 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

最佳答案

for 循环中的每次迭代中尝试 awaitPromise:

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 循环内的最后一次迭代的解决方案 and await 在记录 Done 之前的最终 promise :

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

关于JavaScript 在迭代数组时等待后端响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50207972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com