Promise. All() gets multiple asynchronous requests in the project

Time:2022-5-10

Promise. All() is simply understood as:Multiple promise instances can be combined into a new instance, and the combined promise will become full only when all instances are full. If any instance is rejected, the combined promise will become rejected

 1 const p1 = new Promise((resolve, reject) => {
 2   resolve('success')
 3 })
 4 
 5 const p2 = new Promise((resolve, reject) => {
 6   resolve('success')
 7 })
 8 
 9 const p3 = new Promise((resolve, reject) => {
10   reject('failed')
11 })
12 
13 Promise.all([p1, p2])
14   .then(result => {
15     console.log(result)
16   })
17   .catch(err => {
18     console.log(err)
19   })
20 // ['success', 'success']
21 
22 Promise.all([p1, p3])
23   .then(result => {
24     console.log(result)
25   })
26   .catch(err => {
27     console.log(err)
28   })
29 // failed

Promise. The result of all() is an array in the same order as the passed in promise instance array. If rejected, the first rejected result will be passed in.

If the internal promise instance has a catch method, its own reject will be called when rejecting; otherwise, the external catch will be called.

Use promise. Com in multiple requests All() can achieve the effect that multiple requests are completed at the same time。 The following is an example used in a project:

1 const param =this.postdata
2 Promise.all([this.$post('admin/listBoardDataV2', param), this.$post('admin/listAllTopList', param)])
3     .then(([previousRes, res]) => {
4     // ...      
5 })

Recommended Today

Taro3. 4 example of developing wechat applet

1、 Install scaffolding and initialize project Install scaffold Scaffolding Initialization is shown in the figure below. Select vue3, less and vue3 nutui templates: initialization 2、 Installation package audit and version check After installation, some alarm prompts may appear and prompt NPM audit, as shown in the following figure Installation package audit If you ignore it, […]