Some operations need to be performed after several asynchronous requests are completed, although Ajax can put a complete Ajax callback inside another, but this can easily lead to the callback hell, and the code is also very unsightly.
Fortunately axios provided a method of concurrent requests,
Instructions:
1. ready first plurality of requests, such as get, into an array, [axios.get (url1), axios.get (url2), axios.get (url3)]
2. The request to call an array into axios.all
3. callback parameter is an array, corresponding to the result for each request
Code:
1 let urls = [ 2 'https://jsonplaceholder.typicode.com/posts/1', 3 'https://jsonplaceholder.typicode.com/posts/2', 4 'https://jsonplaceholder.typicode.com/posts/3' 5 ] 6 let axiosList = [] 7 urls.forEach(url => { 8 axiosList.push(axios.get(url)) 9 }) 10 axios.all(axiosList).then(function (res) { 11 let p1 = (res[0].data) 12 let p2 = (res[1].data) 13 console.info(p1) 14 console.info(p2) 15 })
May also be used to spread requests partition, it will be noted that the callback inside different parameters.
1 axios.all(axiosList).then(axios.spread(function (res1, res2, res3, res4) { 2 let p1 = (res1.data) 3 let p2 = (res2.data) 4 console.info(p1) 5 console.info(p2) 6 }))