JS sends multiple requests continuously Promise.all() Promise.race()-Kaiqisan

**JS sends multiple requests in a row Promise.all() Promise.race() **

ヤッハロー, Kaiqisan すうう, 一つふつうの学生プログラマである, yesterday encountered a problem when writing a project, that is, when deleting files in batches, a lot of prompt boxes pop up. After I checked the code, I realized that it was because This batch delete operation is caused by the iterative loop and repeated request routing. Every time a file is deleted, a "Delete Successful" pops up, which will lead to a poor user experience. I wanted to talk to the back-end people, and trouble me to write a batch delete route, but I didn’t do this. The purpose of taking this project was to learn, and I thought that my knowledge of asynchronous requests is still relatively good. Weak, in order to improve myself, I decided to solve this problem by myself through front-end means.
The code below is the original problem code!

this.arr.forEach(item => {
    
    
	// 请求发送正文 
})

I hope that the current asynchronous functions can get a unified return after all executions are completed, so using Promise.all and Promise.race() is the most suitable for current needs. The following is the most standard format of Promise.all.

Promise.all()

Promise.all([a1, a2, a3, a4]).then(res => {
    
    
    
}).catch(err => {
    
    
    
})

Promise.all() must be passed in an array, because the need here requires you to handle multiple asynchronous methods by default. The members inside must be Promise objects with a standardized format, otherwise the return cannot be obtained

let a1 = new Promise((resolve, reject) => {
    
    
    .....
    resolve()
})

Finally, if all the asynchronous methods are executed unharmed, finally go to the method in then and return a res, which is an array that records the return value of all Promises (Promise uses resolve() return value) and the position of the return value It is a step-by-step process. The return value of the first Promise member at the incoming place is in the first member of the res array, and the return value of the second Promise member at the incoming place is in the second member of the res array. analogy.

but

If when running these asynchronous methods, one of the methods has an exception and goes the reject() line , which will cause the entire Promise.all() method to end immediately and output the return value of the failed Promise and follow the catch route. Execute the method inside. This err is the return value of the fault line.

Promise.race()

It Promise.all()has no difference in format and execution flow from the above . The only difference lies in the output value res of the then line Promise.all(). The output value is arranged step by step, but it is not here. It needs to compare the asynchronous execution speed here. , Only output the return value of the first Promise() that is executed. If the first Promise that is executed is returned in the form of resolve(), then take the then route, otherwise take the catch route , after the first Promise is executed The following Promise will never be executed again .

Reference source code

let a1 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve(10)
    }, 100)
})
let a2 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve(12)
    }, 3000)
})
let a3 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve(14)
    }, 1000)
})
let a4 = new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
        resolve(16)
    }, 2000)
})

Promise.all([a1, a2, a3, a4]).then(res => {
    
    
    console.log(res) // [10, 12, 14, 16]
}).catch(err => {
    
    
    console.log(err)
})

Promise.race([a1, a2, a3, a4]).then(res => {
    
    
    console.log(res) // 10
}).catch(err => {
    
    
    console.log(err)
})

Other writing

This method is suitable for some similar asynchronous codes that need to be matched with iteration parameters and executed in batches, which can greatly save the amount of code. This is also the method I used in the current project

Promise.all(this.arr.map((item, i) => {
    
     // map方法迭代之后整合Promise对象为数组
    return new Promise((resolve, reject) => {
    
    
        ....resolve()
        ...reject()
    })
})).then(res => {
    
    
    //
}).catch(err => {
    
    
    //
})

to sum up

Promise.all() is more practical than Promise.race() and is mostly used to send requests in batches.

After solving this problem, although it takes more time to communicate with back-end personnel, I learned new knowledge and got a deeper impression of asynchronous requests. In addition, I wrote this blog. I reviewed this knowledge point again. In the future, I will be able to use this method more proficiently. If I went out for an internship and didn't learn anything, then I would lose out, and the money I took was far less than the employees of other companies, and I haven't learned anything. How can I say it? !

Guess you like

Origin blog.csdn.net/qq_33933205/article/details/108075177