This article records his learning promise experience, if there is wrong place, welcome to point out!!

Basic usage

If you’ve learned Promise, you should know that this is a way for JS to implement async, mainly used to solve the problem of callback hell, so what is callback hell?

When we make an interface request, if we encounter such a situation, after requesting interface A, we use the result of interface A to request interface B, and then use the result of interface B to request interface C……

$.ajax({ url: '/a', success: function(resA) { $.ajax({ url: '/b', data: {a: resA}, success: function(resB){ // ...... }})}})Copy the code

This time the callback function is nested on top of each other, which is one of the cases of the callback hell. The code becomes very unreadable at this point, so we can optimize it with promises.

const a = function() {
    new Promise((res, rej) => {
        $.ajax({
            url: '/a',
            success(data) {
                res(data)        
            }
        })
    })
}

const b = function(dataA){
    return new Promise((res, rej) => {
        $.ajax({
            url: '/b',
            data: {a: dataA},
            success(data) {
                res(data)        
            }
        })    })
}

a().then(data => {
    return b(data)
}).then(data => {
    // ......
})
Copy the code

It looks a lot easier when we change the code to promise.

promise.all

One of the early interviewers asked me, “How can I use Promise to make pictures load sequentially?” At that time, I was not very familiar with the promise.all method, so I didn’t answer it.

The all method means to wait for all promise programs to return results and then execute the subsequent programs as follows:

Let p1 = new Promise((resolve, reject) => {resolve(' resolve ')}) let p2 = new Promise((resolve, reject)) Reject) => {resolve('success')}) let p3 = promse.reject (' failure ') Promise. (p2). Then (result) = > {the console. The log (result) / / [' success ', 'success'] }).catch((error) => { console.log(error) }) Promise.all([p1,p3,p2]).then((result) => { console.log(result) }). The catch ((error) = > {the console. The log (error) / / failed, hit 'failure'})Copy the code

In the above program, there are three promises: P1, P2 and P3, among which P1 and P2 are successfully implemented and P3 is failed.

When we use the all method to listen on P1 and P2, because all the monitored promises are successful, the program enters the then function and receives the parameter result as an array, and each item of the array is the parameter returned by each item of the corresponding listening order.

Let’s go back to the interviewer’s question. Suppose we have 10 images. Although each image takes a different time to load, we can render them to the page in order after all the images are loaded.

When we use all to listen on P1, P2 and P3, the execution of P3 fails, so the program enters the catch. This error receives the value returned by the failed program.

promise.race

let p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve('success') },1000) }) let p2 = new Promise((resolve, reject) => { setTimeout(() => { reject('failed') }, 500) }) Promise.race([p1, Then ((result) => {console.log(result)}). Catch ((error) => {console.log(error) // 打 算 'failed'})Copy the code

The race method says that when any execution of an item in the program is complete, subsequent then or catch is executed.

The p2 program in the example was executed in 0.5s, so the program entered the catch function.

When both programs are successful, which promise completes first, then receives its arguments and then does not trigger the then function

Thank you for watching!!

Kudos!!