This is the 9th day of my participation in the August More Text Challenge, for more details: August more Text Challenge!

Definition:

Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively.

A Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way.

How many states does a Promise have?

There are three states: Pending, Resolved and Rejected

Here’s an example:

let HelloPromise = new Promise((resolve, reject) => {
  // code
  resolve('success')
  // code 
  reject('failed') 
})

HelloPromise.then((res) => {
  console.log(res)
}, (result) => {
  console.log(res)
})
Copy the code

Is the state of the Promise mutable?

immutable

1. The status of the object is not affected. The Promise object represents an asynchronous operation with three states: Pending, fulfilled and Rejected. Only the result of an asynchronous operation can determine the current state, and no other operation can change the state. That’s where the name “Promise” comes from. Its English name means “Promise,” indicating that nothing else can change it.

2. Once the state changes, it will never change again. This result can be obtained at any time. There are only two possibilities for the state of the Promise object to change from pending to depressing and from pending to Rejected. As long as these two things are happening the state is fixed, it’s not going to change, it’s going to stay the same and that’s called resolved. If the change has already occurred, you can add a callback to the Promise object and get the same result immediately. This is quite different from an Event, which has the characteristic that if you miss it and listen again, you will not get the result.

Promise:

then

The then method returns a new Promise instance (note, not the original Promise instance), so you can use chained notation, where the then method is followed by another then method.

getData('/getDataTable').then(function(json) {
  return data;
}).then(function(post) {
  // ...
});
Copy the code

catch

The promise.prototype.catch () method is an alias for. Then (null, Rejection) or. Then (undefined, Rejection) that specifies the callback when an error occurs. Ex. :

getData('/getDataTable').then(function(posts) { // ... }). Catch (function(error) {// Handle getData and the previous callback function running error console.log(' error! ', error); });Copy the code

finally

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

Promise. Then (result = > {...}). The catch (error = > {...}), finally (() = > {...});Copy the code

all

The promise.all method is used to wrap multiple Promise instances into a new Promise instance

const promises = [2, 3, 5, 7, 11, 13].map(function (id) {
  return getJSON('/post/' + id + ".json");
});

Promise.all(promises).then(function (posts) {
  // ...
}).catch(function(reason){
  // ...
});
Copy the code

Promises are an array of six Promise instances. Only when the states of the six Promise instances become fulfilled or one of them becomes Rejected, will the callback function behind Promise.

race

The promise.race () method again wraps multiple Promise instances into a new Promise instance

const p = Promise.race([
  fetch('/resource-that-may-take-a-while'),
  new Promise(function (resolve, reject) {
    setTimeout(() => reject(new Error('request timeout')), 1000)
  })
]);

p
.then(console.log)
.catch(console.error);
Copy the code

In the code above, if the fetch method fails to return a result within 1 second, the status of the variable P changes to Rejected, which triggers the callback specified by the catch method