The definition of Promise

Pormise is a solution to ASYNCHRONOUS programming of JS, which was written into the language standard in ES6 and provides native Promise objects.

Promises are simply a container that holds the result of an event that will end in the future. Promise is an object from which you can retrieve messages for asynchronous operations, and promises provide a unified API from which asynchronous operations can be handled in the same way.

Promise has the following two features:

  1. The status of an object is not affected. This is a big pity, which is a pity and rejected. Only the result of an asynchronous operation can determine the current state, and no other operation can change the state.

  2. Once the state changes, it never changes again, and you can get this result at any time. There are only three states from padding to disappointing or from padding to Rejected. There are only two changes from the padding to a fulfilled or refected state.

With the Promise object, asynchronous operations can be expressed as a flow of synchronous operations, avoiding layers of nested callback functions. In addition, Promise objects provide a unified interface that makes it easier to control asynchronous operations.

The drawbacks of promises

  1. There is no way to cancel a Promise, which is executed as soon as it is created and cannot be cancelled halfway through.

  2. If the callback function is not set, errors thrown inside a Promise are not reflected outside.

  3. When you are in a pending state, you have no way of knowing what stage of progress you are currently in (just started or about to complete).

Promise basic usage

const promise = new Promise((resolve, reject) => {
  let status = true;
  if (status) {
    resolve('Operation successful! ');
  } else {
    reject('Operation failed! '); }}); promise.then(res => { console.log('Successful result:' + res);
}, error => {
  console.log('Failure result:' + error);
  
});
Copy the code

In ES6, the Promise object is a constructor that generates a Promise instance. The Promise constructor takes a function as an argument and two arguments, resolve and reject.

The resolve function changes the state of the Promise from the padding to the fufilled; The reject function changes the state of the Promise from the padding to rejected.

After the Promise instance is produced, you can use the THEN method to specify the fufilled and Rejected state callback functions, respectively.

The then method takes two arguments. The first callback is called when the state changes to fufilled, and the second callback is called when the state changes to refected. The second parameter is optional and does not have to be supplied.

const promise = new Promise((resolve, reject) => {
  console.log('new Promise()');
  resolve();
});

promise.then(() => {
  console.log('resolve()');
});

console.log('End');
Copy the code

Here’s a simple version of the Promise pair, and let’s see how it works in the example above.

New Promise() End resolve()Copy the code

In the example above, the Promise object is printed first because it is synchronous, and the then method is asynchronous so it is printed later.

The grammar sugar then of Promise

Promise instances have then methods defined on the prototype object Promise.Prototype. The first callback is called when the state changes Fufilled, and the second callback (optional) is called when the state changes Rejected.

new Promise((resolve, reject) => {
  resolve('Wang Xiaoduan Coder'); }).then(res => { console.log(res); });Copy the code

Then method, which can write a callback method to execute a successful callback. The THEN method returns a new Promise instance, so we can use chained notation, where the THEN method is followed by a then method.

new Promise((resolve, reject) => {
  resolve('Wang Xiaoduan Coder'); }).then(res => res).then(res => { console.log(res); });Copy the code

Using chained THEN, you can specify a set of callback functions that are called in order. In this case, the previous callback may still return a Promise object (with asynchronous operations), and the latter callback will wait for the state of the Promise object to change before it is invoked.

The syntax sugar catch of Promise

A catch is a callback that specifies an error.

new Promise((resolve, reject) => {
  reject('failure'); }).catch(error => { console.log(error); / / fail});Copy the code

The Promise instance is caught by the Catch method when its state changes to rejected or when an operation fails to throw an exception. So in a Promise instance, reject is equivalent to throwing an error. If the Promise state has changed to Resolved, throw an error void.

new Promise((resolve, reject) => {
  reject('failure');
  throw new Error('Throw exception'); // This line is invalid}). Catch (error => {console.log(error); / / fail});Copy the code

Promise’s finally method

The finally method is used to specify actions that will be performed regardless of the final state of the Promis object. This method was introduced as a standard in ES2018.

new Promise((resolve, reject) => {
  resolve();
}).then(res => {
  console.log('success');
}).catch(error => {
  console.log('error');
}).finally(() =>{
  console.log('finally');
})
Copy the code

Promise’s all method

The promise.all method is used to wrap multiple Promise instances into a new Promise instance. This will be a pity. If the state of all Promise objects returns fufilled, the fulfilled Promise will be returned. Otherwise, the fulfilled Promise will be returned.

const promise1 = new Promise((resolve, reject) => {
  resolve();
})
const promise2 = new Promise((resolve, reject) => {
  resolve();
})
const promise3 = new Promise((resolve, reject) => {
  resolve();
})

const promiseAll = Promise.all([promise1, promise2, promise3]).then(res => {
  console.log('all');
})
Copy the code

Promise’s RACE method

The promise.race method also wraps multiple Promise instances into a new Promise instance. Multiple Promise objects can be passed as arguments, and if the instance red has one of the first instances to change state, the state of the race will change.

const promise1 = new Promise((resolve, reject) => {
  reject();
})
const promise2 = new Promise((resolve, reject) => {
  resolve();
})
const promise3 = new Promise((resolve, reject) => {
  reject();
})

const promiseRace = Promise.race([promise1, promise2, promise3]).then(res => {
  console.log('race then');
}).catch(error => {
  console.log('race catch');
})
Copy the code

Promise to end! Thank you for pointing out the shortcomings.