Vue: Use Promise.all() method to execute multiple requests in parallel

In Vue, you can use the Promise.all() method to execute multiple requests in parallel. When you need to execute multiple asynchronous requests at the same time, you can encapsulate these requests as Promise objects and use the Promise.all() method to execute them.

Example 1:

The following is a sample code showing how to execute multiple requests in parallel via the Promise.all() method:

//定义多个请求
const request1 = axios.get('/api/data1');
const request2 = axios.get('/api/data2');
const request3 = axios.get('/api/data3');

//使用Promise.all()方法执行多个请求
Promise.all([request1, request2, request3])
  .then(function (results) {
    
    
    //results包含了所有请求的结果
    const data1 = results[0].data;
    const data2 = results[1].data;
    const data3 = results[2].data;
    //TODO 处理请求结果
  })
  .catch(function (error) {
    
    
    //TODO 处理请求错误
  });

In the above example, three requests are defined: request1, request2, request3. Then, use the Promise.all() method to fulfill those requests. When all requests return successfully, the Promise.all() method will return an array containing the results of all requests. The result of each request can be obtained by indexing into the array. If any one of these requests fails, the Promise.all() method will immediately trigger the catch() method and return an error message.

This way of executing multiple requests in parallel can significantly improve the performance and response speed of the program. Because multiple requests can be in progress at the same time, there is no need to wait for each request to complete before executing the next one.

Example 2:

let [res1, res2] = await Promise.all([
	request({
    
    
	  url: '/api/data1',
	  method: 'get',
	  params: params1
	}),
	request({
    
    
	  url: '/api/data2',
	  method: 'get',
	  params: params2
	})
]);
console.log('res1',res1,'res2',res2);

Guess you like

Origin blog.csdn.net/weixin_46098577/article/details/132302715