gpt4 book ai didi

javascript - 嵌套的 Axios 调用只返回第一个值到数组

转载 作者:行者123 更新时间:2023-12-04 07:15:43 26 4
gpt4 key购买 nike

我在另一个调用中嵌套了一个 Axios 调用,以便从我的第一个调用中获取 ID 列表,然后循环遍历每个 ID,从第二个 API 调用中获取状态。它只会在我记录阵列时返回第一个状态,而不是显示完整阵列。
我相信问题可能出在 promise 链中……或者如果这不是在输出最终数组之前等待 promise 完成。

    var responsearray = [] 

axios.get('https://myapi.net/api/role/allroles?pageSize=1000').then(function (response) {

for(var i = 0; i < response.data.roles.length; i++)
{
var entry = response.data.roles[i];
var entryid = entry.id;

return axios.get('https://myapi.net/api/role/score/' + entryid).then(function (response2) {
// Nested call per role to push to array
responsearray.push(response2.status)
});
}

}).catch(function (error) {
// handle error
console.log(error);

}).then(function () {
// always executed
// Return Array
console.log(responsearray);
});

最佳答案

看起来外部 promise 正在被解析,因为您正在返回一个值(这是第一个内部 promise ,第一个 Axios 循环内的调用)。
然后,当外部 promise 解决时,外部 then正在使用 responsearray 调用函数恰好保存了第一个 response2 的结果(但是它甚至可能是空的,因为第二个 Axios 调用可能尚未解决)。
所以流程是这样的:First axios call => first Then is called => i=0, second axios call is **RETURNED** => first axios call is resolved => last then is called => (second axios may be resolved by now and responsearray is filled with the result for i=0) => console.log(responsearray)无论如何,我建议使用 Promise.all这会给你一个包含一系列 promise 的 promise ,并且只有在所有 promise 都得到解决时才能解决它。您可以阅读更多相关信息 here .
我会像这样使用它:

var responsearray = [] 

axios.get('https://myapi.net/api/role/allroles?pageSize=1000').then(function (response) {

for(var i = 0; i < response.data.roles.length; i++)
{
var entry = response.data.roles[i];
var entryid = entry.id;

//pushing the promise into responsearray
responsearray.push(axios.get('https://myapi.net/api/role/score/' + entryid).then(function (response2) {
console.log(i + " resolved");
}).catch(function (error) {
// handle error
console.log(error);
});
})
console.log("Done pushing all the promises");
return responsearray;

}).catch(function (error) {
// handle error
console.log(error);
}).then(function (responsearray) {
console.log("outer axios is resolved");
// responsearray should have all the promises by now
Promise.all(responsearray).then((results) => {
console.log(results);
}).catch(function (error) {
// handle error
console.log(error);
});
});

关于javascript - 嵌套的 Axios 调用只返回第一个值到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68778497/

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