[英]how to do chained axios requests in multiple loop?
Here is the condition: there are three requests:这是条件:有三个请求:
the Axios_Request_1 returns an array => Array_1 Axios_Request_1 返回一个数组 => Array_1
now the Axios_Request_2 go through the Array_1,with all response data get Array_2现在Axios_Request_2 go通过Array_1,所有响应数据得到Array_2
the last request Axios_Request_3 go through Array_2.最后通过 Array_2 请求 Axios_Request_3 go。 and generate the desired Array_3 I konw with promise.all it could be done like this
并生成所需的 Array_3 我知道 promise.all 可以这样做
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)
But it's slower than what I wanted like this:但它比我想要的慢:
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);
It doesnot work as i want.它不能按我的意愿工作。 And I tried to put promise.all but doesnot work or I just didnot get it working well,I wonder what can i do to generate result through code like the second one
我试着把 promise.all 但不起作用或者我只是没有让它工作得很好,我想知道我能做些什么来像第二个那样通过代码生成结果
Chain the Axios_Request_3
call immediately onto the Axios_Request_2
, so that 3 fires as soon as that 2 is done, rather than having to wait for all 2s to finish.立即将
Axios_Request_3
调用链接到Axios_Request_2
上,以便3 在 2 完成后立即触发,而不必等待所有 2 完成。
I'd also highly recommend following the standard JavaScript naming conventions - use camelCase
for functions and most variables.我还强烈建议遵循标准的 JavaScript 命名约定——对函数和大多数变量使用
camelCase
命名法。
const array1 = await axiosRequest1;
const output = await Promise.all(
array1.map(
ca => axiosRequest2(ca)
.then(subarray2 => Promise.all(
subarray2.map(axiosRequest3)
))
)
);
Might be easier to visualize with a separate named function beforehand.事先使用单独的名称 function 可能更容易可视化。
const getProductsFromSubarray = subarray2 => Promise.all(subarray2.map(axiosRequest3));
const array1 = await axiosRequest1;
const output = await Promise.all(
array1.map(
ca => axiosRequest2(ca).then(getProductsFromSubarray)
)
);
Still, depending on the size of the input array and the size of the responses, there could still be a whole lot of requests to be made in total, so that could be another significant cause of the app feeling slow.不过,根据输入数组的大小和响应的大小,仍然可能需要发出大量请求,因此这可能是应用运行缓慢的另一个重要原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.