gpt4 book ai didi

javascript - NodeJs 等到循环中的所有调用都完成

转载 作者:行者123 更新时间:2023-12-05 02:32:28 25 4
gpt4 key购买 nike

我在 Node (初学者)中有以下代码,我想在循环中执行完所有代码后调用一个函数,我知道我必须使用 promise ,但我不知道如何应用它们在这个情况下。代码已被简化。非常感谢。

const axios = require('axios').default;

axios.post('url', {
params: {}
}).then(response=>{
var objResponse = response.data
Object.keys(objResponse).forEach(function (key){
axios.post('url', {
params: {}
}).then(response=>{
var n=0;
getCode(n);
})
})
**finishFunction**()
})

function getCode(n) {
axios.post('url', {
params: {}
}).then(response=>{
if(response.data){
if (response.data.code) {
getData();
}else{
if (n < 10) {
n++;
getCode(n);
} else {
getTimeout();
}
}
}
})
}

function getTimeout() {
axios.post('url', {
params: {}
})
}

function getData() {
axios.post('url', {
params: {}
}).then(response=>{
console.log('finished one loop');
})
}

最佳答案

实现您想要的效果的最佳方法是使用带有常规 for 循环的 async/await。

这是我的意思的一个例子。您可以根据需要进行调整:

async doSomeStuff() {
const results = []

const res1 = await axios.post('url', {
params: {}
})

// assuming res1 is an Array
for (let i=0; i < res1.length; i++) {
const result = await axios.post('url2', {
params: {}
})
results.push(result)

}

return results
}

您还可以在循环中调用其他异步函数。

关于javascript - NodeJs 等到循环中的所有调用都完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71228885/

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