简体   繁体   中英

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
now the Axios_Request_2 go through the Array_1,with all response data get Array_2
the last request Axios_Request_3 go through Array_2. and generate the desired Array_3 I konw with promise.all it could be done like this

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

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.

I'd also highly recommend following the standard JavaScript naming conventions - use camelCase for functions and most variables.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM