gpt4 book ai didi

javascript - 执行循环体中的异步代码后如何开始执行某些代码?

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

例如这段代码写道:“我在这里!”然后“0、1、2、3...”

for(let i=0; i<=10; i++) {
//some async code
setTimeout(function(){
console.log(i);
}, 2000);
}
console.log("Here I am!");

如何从循环中获取结果,然后执行下一部分代码?获得:“0, 1, 2, 3 ... 10”,然后“我在这里!”?

最佳答案

您可以将异步代码包装在 Promise 中,然后使用 Promise.all() 等待结果。然后在 then 中打印“Here am I”

function A(i){
return new Promise((resolve, reject) => {
setTimeout(function(){
resolve(i);
}, 2000);

})
}
let promiseArray = [];
for(let i=0; i<=10; i++) {
//some async code
promiseArray.push(A(i));
}

Promise.all(promiseArray).then((result) => {
console.log(result);
console.log("Here I am!");
})

关于javascript - 执行循环体中的异步代码后如何开始执行某些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46257135/

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