Promise is an asynchronous programming solution that makes it easy to handle asynchronous events. A Promise instance contains an asynchronous operation that has only three states: Pending initial state, which is neither successful nor failed, Resolved successfully completed, and Rejected.

The Promise state is unaffected and once the state changes, it never changes.

Create a Promise

To create a Promise instance, you use the Promise class, which takes a function as an argument that takes two arguments, also functions, one that needs to be called if the asynchrony succeeds and one that needs to be called if the asynchrony fails.

The parameter function that creates the Promise instance will execute immediately.

function getData(url) {
    return new Promise((resolve, reject) = > {
        const xhr = new XMLHttpRequest();"GET", url);
        xhr.onload = (a)= > resolve(xhr.responseText); 
        // Change the state to Resolved and pass in the obtained data
        xhr.onerror = (a)= > reject(xhr.statusText);
        // Change the status to Rejected and pass an error messagexhr.send(); })}// Calling getData returns a Promise instance
Copy the code

The prototype approach for Promise

There are three prototype methods for promises: then, Catch, and finally.


The then method takes two function arguments, one to be executed on success and one to be executed on failure.

And the then method will return a new Promise instance, which means you can chain.

Call the Promise of Resolve immediately, and the argument function of its then method is placed at the end of the event loop.

let p1 = getData('')

let onFulfilled = data= > console.log(data)
let onRejected = err= > console.log(err)

p1.then(onFulfilled, onRejected)

// Ondepressing will call the first callback function when it succeeds, and pass all the parameters passed to Resolve into ondepressing

// The second callback is called when it succeeds and all the arguments passed to resolve are passed to onRejected

let p2 = getData('')

p2.then(url= > getData(url))
  .then(data= > console.log(data)) // chain operation
// ------------------

let p = new Promise(resolve= > {

setTimeout((a)= > console.log(4))
p.then(num= > console.log(num))
// The printing order is 1, 2, 3, 4

Copy the code


The catch method accepts a function argument, onRejected, which is the second argument to then.

The catch method is going to be at the end, and the then method is going to bubble up to it.

Catch again returns a Promise object. But a catch can’t catch an error thrown by a later then method and of course a catch method can throw an error.

let p3 = getData('')

p3.then(data= > console.log(data))
  .then((a)= > throw new Error('error')) // Throw an error
  .then((a)= > console.log(1))
  .catch(err= > console.log(err))
// Catch will catch the above error, and the third then method will be skipped
Copy the code

An uncaught error in a Promise does not terminate script execution but prints an uncaught Promise error.


The finally method takes a function argument, onFinally. It performs the action regardless of the final state of the Promise object. The callback function of the finally method takes no arguments.

It returns a Promise object with the finally callback set.

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value= > P.resolve(callback()).then((a)= > value),
    reason => P.resolve(callback()).then((a)= > { throw reason })

// finally returns a then method that already takes two arguments
Copy the code

Promise method

There are four static methods of promises. They are all, Race, Resolve and Reject.


Resolve takes a parameter and returns a Promise object whose state is determined by the given value.

If the argument is a Promise object, return it.

If the argument is Thenable (that is, the object with the THEN method), the THEN method is executed immediately as an argument to the Promise.

If another value returns a new Promise object in the resolved state, that value is passed to the corresponding THEN method.

Promise.resolve(1).then(num= > {
Copy the code


The Reject method takes an argument, returns a Promise object in a failed state, and passes the given failure information to the corresponding processing method.

/ / is equivalent to
new Promise((resolve, reject) = > reject('error'))
Copy the code


The all method takes an iterable interface parameter.

This method returns a new promise that will succeed only if all of the iterable promise objects succeed, or if any of the iterable promise objects fail.

The new Promise object, after firing the success state, returns the success callback with an array of all the promise returns from iterable, in the same order as the iterable

If the new Promise triggers a failed state, it treats the error message from the first promise in iterable that triggers a failed state as its failed error message.

Each item in the parameter is a Promise object; if it is not, it is converted to a Promise object using the resolve method.


The race method is the same as the All method, but when any child Promise in the Iterable argument succeeds or fails, the state of the returned Promise object changes to that child Promise. Its value or error message is also passed to the callback function that returns the Promise object.

The attribute of Promise

Promise has two properties, Length and Prototype.

The length property, whose value is always 1 (the number of constructor arguments).