What is Promise?

Promise is an elegant solution to asynchronous programming. It is more reasonable and powerful than callbacks and event interactions. It ameliorates the problem of deep pullbacks. There are callbacks inside callbacks, and the deeper ones, the code looks really messy. Interaction with events will do more work, such as sending events, listening to events, event callback operations. The Promise gets the results of the asynchronous operation so that you can work with the logic that follows.

A Promise, simply put, is a container that holds the result of some event (usually an asynchronous operation) that will end in the future. ES6 writes this into the language standard and provides Promise objects natively.

The characteristics of the Promise

  1. The Promise object represents an asynchronous operation. There are three states :Pending, FulFilled and Rejected. No other operation can change this state. That’s where the name “Promise” comes from. It means “Promise” in English and cannot be changed by other means.
  2. Once the state changes, it never changes. You can get this at any time. There are only two possibilities for the state of a Promise object to change: from Pending to depressing, or from Pending to Rejected. As long as these two things happen, the state will never change.

With the Promise object, you can express asynchronous operations as a flow of synchronous operations. Layers of nested callbacks are avoided. In addition, Promise objects provide a unified interface to the outside world, making it easier to control asynchronous operations.

Promises also have a few downsides: once they start, they are immediately implemented and cannot be cancelled. This is a Promise!

Second, if you don’t set up a callback function, exceptions inside a Promise won’t be reflected outside, meaning you won’t even know what went wrong inside. Furthermore, when in the Pending state, there is no way to know where the progress is, whether it has just begun or is about to be completed

How do I use Promise?

ES6 specifies that a Promise object is a constructor that generates a Promise object. The following code reflects the basic use of Promise.

var promise = new Promise(function(resolve,reject){
    //some code
    if(Operation successful){resolve(value); }else{ reject(error); }})Copy the code

Promise’s constructor takes as an argument a function called resolve and reject, two functions that are provided by the JavaScript engine and not deployed by the developer.

The function of resolve is to change the Promise state from Pending to Fulfilled. It will be called when the asynchronous operation succeeds and pass the result of the asynchronous operation as a parameter. Reject changes the Promise state from Pending to Rejected. It is called when the asynchronous operation fails and passes the error of the asynchronous operation as a parameter.

Promise.prototype.then

A Promise instance has a then method, defined on Promise.Prototype, that adds a callback function to the Promise instance when the state callback changes. The first argument to then is the callback in the Resolved state, and the second argument (optional) is the callback in the Rejected state. The then method returns a new Promise object. Note that this is not the original Promise object, so you can write it chained, meaning you can call the THEN method after the then method.

Give me an example

let promise = new Promise((resolve, reject) = > {
    console.log("Promise!");
    resolve();
    console.log("Promise Over");
})

setTimeout(() = > {
    console.log("Hello World!");
}, 0)

console.log("Hi!");

promise.then(() = > {
    console.log("Resolved!");
})
Copy the code

The operation screenshot is as follows:

Once a promise is created, it will execute immediately. If the code executes synchronously, first it prints a promise, then it prints a promise Over. Because the Promise sequence of operations (then, catch) has a higher priority than setTimeout and then executes promise.then, output Resolved! , and finally execute setTimeout to print Hello World.

Promise.prototype.catch

The promise.prototype. catch method is an alias for. Then (null,reject), which specifies the error callback. A catch catches exceptions thrown from within all promise objects before it.

Here’s an example:

var doSomething = () = > {
    return new Promise((resolve, reject) = > {
        console.log("doSomething");
        resolve(1 + x);
        console.log("doSomething over");
    })
}

doSomething().then((value) = > {
    console.log(value)
}).catch((err) = > {
    console.log("hhhhhh");
    console.log(err);
})
Copy the code

The operation screenshot is as follows:

Promise.all

The promise.all method wraps multiple Promise instances into a new Promise instance.

var p = Promise.all([p1,p2,p3])
Copy the code

In the code above, the promise. all method takes an array of parameters. P1, P2, and p3 are all instances of the Promise object. If they are not, the Promise. (The promise. all method can take arguments that are not arrays, but must have an Iterator interface and return each member as a Promise instance.)

The state of P is determined by P1, P2 and P3, which can be divided into two cases. (1) Only when the states of P1, P2 and P3 become depressing, the state of P will become depressing. At this time, the return values of P1, P2 and P3 will form an array and be passed to the callback function of P. (2) As long as p1, P2 and P3 are rejected, P becomes rejected, and the return value of the first rejected instance is passed to p’s callback function

Here’s an example:

let promise1 = new Promise(resolve= > {
    console.log("promise1");
    resolve(1);
})

let promise2 = new Promise(resolve= > {
    console.log("promise2");
    resolve(2);
})

let promise3 = new Promise(resolve= > {
    console.log("promise3");
    resolve(3);
})

let promises = [promise1, promise2, promise3];

Promise.all(promises).then(value= > {
    console.log(value);
}).catch(err= > {
    console.log(err);
})
Copy the code

Run screenshot:

Look at another chestnut:

let promise1 = new Promise(resolve => {
    console.log("promise1");
    resolve(1);
})

let promise2 = new Promise(resolve => {
    console.log("promise2");
    resolve(2);
})

let promise3 = new Promise(resolve => {
    console.log("promise3");
    resolve(x + 3);
}).then((value) => {
    console.log(value);
})


let promises = [promise1, promise2, promise3];

Promise.all(promises).then(value => {
    console.log(value);
}).catch(err => {
    console.log("promise all err:", err);
})
Copy the code

Run screenshot:

In the code, promisE1 and promise2 are in the resolved state, and promise3 is in the Rejected state. All the Promise also changes to the Rejected state. So the catch method after promise. all is executed, so promise1, promise2, promise3 is printed, and the Promise All Err is printed.

Look at another chestnut:

let promise1 = new Promise(resolve => {
    console.log("promise1");
    resolve(1);
})

let promise2 = new Promise(resolve => {
    console.log("promise2");
    resolve(2);
})

let promise3 = new Promise(resolve => {
    console.log("promise3");
    resolve(x + 3);
}).then((value) => {
    console.log(value);
}).catch((err) => {
    console.log("promise3 err:", err);
})


let promises = [promise1, promise2, promise3];

Promise.all(promises).then(value => {
    console.log(value);
}).catch(err => {
    console.log("promise all err:", err);
})
Copy the code

Run screenshot:

Analysis: Promise1, promisE2 will be in resolved state, and when we get to promise3, if there’s an error in promise3, then the catch method that follows promise3 will execute, and the catch method will return a new Promise instance, Promise3 points to this new promise instance. This instance will also be in the Resolved state after a catch. So promise1, promise2, and promise3 are in resolved state, so promise1, promise2, and promise3 are in resolved state, so promise1, promise2, and promise3 are in resolved state, so promise1, promise2, and promise3 are in resolved state. So it prints [1,2,undefined].

Promise.race

The promise.race method also wraps multiple Promise instances into a new Promise instance.

var p = Promise.race([p1,p2,p3])
Copy the code

In the above code, the state of P changes as long as one of the first instances of P1, P2, and P3 changes state. The return value of the first changed Promise instance is passed to p’s callback. The parameters of the promise.race method are the same as those of the promise.all method. If it is not a Promise instance, the promise.resolve method, described below, is first called to convert the parameters to a Promise instance, and then further processing.

Here’s an example:

let promise1 = new Promise(resolve= > {
    console.log("promise1");
    resolve(1);
})

let promise2 = new Promise(resolve= > {
    console.log("promise2");
    resolve(2);
})

let promise3 = new Promise(resolve= > {
    console.log("promise3");
    resolve(3);
})

let promises = [promise1, promise2, promise3];

Promise.race(promises).then(value= > {
    console.log(value);
}).catch(err= > {
    console.log(err);
})
Copy the code

Run screenshot:

Promise.resolve

Promise. Resolve transforms an object into a Promise object.

The parameters of the promise.resolve method are divided into four cases.

  1. The argument is a Promise instance. If the argument is a Promise instance, promse. resolve will return the instance unchanged.
  2. The argument is a Thenable object

    Thenable objects refer to objects that have then methods. Like this object right here
    let thenable = {
        then:function(resolve,reject){
            resolve(12);
        }
    }
    
    let p = Promise.resolve(thenable);
    p.then((value)=>{
        console.log(value);
    })
    Copy the code

    The promise. resolve method converts this object to a Promise object and then immediately executes the thenable object’s then method. All of the above code will print 12.

  3. If the parameter is a primitive value, or an object that does not have a THEN method, promise.resolve will return a new Promise object with the state Resolved
    Var p = promise.resolve ("Hello"); p.then((s)=>{ console.log(s) })Copy the code

    The code above prints Hello.

  4. Promise with no arguments. Resolve allows calls with no arguments. Instead, return an Resolved Promise object.

    Note that the resolve Now Promise object is at the end of this event cycle and at the beginning of the next.

    Here’s an example:
    setTimeout(() => {
        console.log("xxxx");
    }, 0);
    
    Promise.resolve().then(() => {
        console.log("yyyyy");
    })
    
    console.log("zzzz");
    Copy the code

    Run screenshot:

Promise.reject

The promise.reject (Reason) method also returns a new Promise instance with the state Rejected.

Promise.finally

The finally method is used to specify actions that will be performed regardless of the final state of the Promise object.

Here’s an example:

let p2 = new Promise((resolve, reject) => {
    resolve(1);
})

p2.then((value) => {
    console.log(value);
}).catch((err) => {
    console.log("error:", err);
}).finally(() => {
    console.log("finally");
})
Copy the code

Output: 1 finally

So, Promise, are you familiar with it? There will be more stories about Promise, so stay tuned

If there is a mistake, huan drink big guys clap brick ~