乐闻世界logo
搜索文章和话题

How to post multiple Axios requests at the same time?

1个答案

1

When you need to initiate multiple Axios requests simultaneously, you can combine axios.all() with axios.spread(). The axios.all() method allows you to execute multiple requests in parallel, while axios.spread() enables you to process the responses of these requests.

Here is an example demonstrating how to initiate two requests simultaneously:

javascript
import axios from 'axios'; function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } // Using `axios.all()` to issue two requests in parallel axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread((acct, perms) => { // When both requests are completed, this callback is executed // acct and perms are respectively the responses of the two requests console.log('User Account', acct.data); console.log('User Permissions', perms.data); })) .catch(error => { console.error('An error occurred:', error); });

In the above code, the getUserAccount and getUserPermissions functions respectively issue two HTTP GET requests. Using axios.all(), these two requests are combined and executed in parallel. When all requests are completed, the axios.spread() callback is invoked and receives each response as a parameter.

Since ES6 introduced Promise, we can also use Promise.all to achieve similar functionality, as shown in the following example:

javascript
Promise.all([getUserAccount(), getUserPermissions()]) .then(([acct, perms]) => { // When both requests successfully complete, this callback is executed console.log('User Account', acct.data); console.log('User Permissions', perms.data); }) .catch(error => { // If any request fails, this callback is executed console.error('An error occurred:', error); });

Here, Promise.all() is used to wait for all given Promise objects to complete successfully. If all requests succeed, their responses are passed as an array to the callback function of .then(). Otherwise, if any request fails, .catch() captures the reason for the failure. This approach offers better compatibility and is more commonly used in modern JavaScript development.

2024年6月29日 12:07 回复

你的答案