如何在多个循环中做链接axios请求?



条件如下:有三个请求:
Axios_Request_1返回一个数组=>Array_1
现在Axios_Request_2通过Array_1,所有的响应数据得到Array_2
最后一个请求Axios_Request_3通过Array_2。生成所需的Array_3我知道,我保证。就像这样

let Array_1 = await Axios_Request_1
let Promise_1 = []
for (const ca of Arrya_1) {
Promise_1.push(Axios_Request_2(ca))
}
let Array_2 = await Promise.all(Promise_1)
let Promise_2 = []
for (const product of Array_2) {
Promise_2.push(Axios_Request_3(product ))
}
let Array_3 = await Promise.all(Promise_2)

但是它比我想要的慢:

let Array_3 = []
Axios_Request_1.then(function(Array_1){
for (const ca of Array_1) {
Axios_Request_2(ca).then(Subarray_Array_2=>{
for (const product of Subarray_Array_2) {
Axios_Request_3(product).then(element_Array_3=>{
Array_3.push(element_Array_3)
})
})
})
console.log(Array_3);

它不像我想要的那样工作。我试着承诺。所有,但不工作,或者我只是没有得到它的工作很好,我想知道我能做些什么来生成结果通过代码像第二个

Axios_Request_3调用立即链接到Axios_Request_2上,以便在2完成时立即触发3,而不是等待所有2s完成。

我还强烈建议遵循标准的JavaScript命名约定——对函数和大多数变量使用camelCase

const array1 = await axiosRequest1;
const output = await Promise.all(
array1.map(
ca => axiosRequest2(ca)
.then(subarray2 => Promise.all(
subarray2.map(axiosRequest3)
))
)
);

如果事先使用单独的命名函数,可能会更容易可视化。

const getProductsFromSubarray = subarray2 => Promise.all(subarray2.map(axiosRequest3));
const array1 = await axiosRequest1;
const output = await Promise.all(
array1.map(
ca => axiosRequest2(ca).then(getProductsFromSubarray)
)
);

但是,根据输入数组的大小和响应的大小,总共仍然可能有很多请求,所以这可能是应用程序感觉缓慢的另一个重要原因。

最新更新