What is Promise? What problem do we solve with Promise?

Promises are a solution to asynchronous programming: syntactically, promises are an object from which to retrieve messages for asynchronous operations; In its original sense, it is a promise that will give you results over time. Promise has three states: pending, fulfiled, and Rejected. Once the state has changed, it will never change. Once a Promise instance is created, it executes immediately.

I’m sure you often write code like this:

Fn2 function fn1(a, fn2) {if (a > 10 && typeof fn2 == 'function') {fn2()}} fn1(11, typeof fn2 == 'function') {fn2()}} Function () {console.log('this is a callback')})Copy the code

In general, we don’t see a lot of callback nesting, usually one or two levels, but in some cases, when a lot of callback nesting, the code can be very cumbersome, which can cause a lot of trouble in our programming. This situation is commonly known as callback hell. And that’s where our promise came in

Promises are designed to solve two problems:

The callback hell, the code is difficult to maintain, and often the output of the first function is the input of the second function. Promise can support multiple concurrent requests, and retrieve the data in the concurrent request. This promise can solve the problem of asynchrony

Es6 promise

Promise is a constructor with familiar methods all, Reject, and resolve on its own, and equally familiar methods like THEN and catch on its prototype.

Let p = new Promise((resolve, reject) => {// do something asynchronous setTimeout(() => {console.log(' done '); Resolve (' I am success!! '); }, 2000); });Copy the code

The Promise constructor takes one argument: the function, and this function takes two arguments:

Resolve: Callback function after asynchronous operation is successfully executed

Reject: Callback function when an asynchronous operation fails

Then chain operation usage

Therefore, on the surface, Promise can only simplify the writing method of layer upon layer callback. In essence, the essence of Promise is “state”, which can be invoked in time by maintaining state and transferring state. It is much simpler and more flexible than passing callback function. So the correct scenario for using promises looks like this:

p.then((data) => {
    console.log(data);
})
.then((data) => {
    console.log(data);
})
.then((data) => {
    console.log(data);
});
Copy the code

Reject:

Set the state of the Promise to Rejected so that we can capture it in THEN and perform the “failed” callback. Look at the code below.

SetTimeout (function(){var num = math.ceil (math.random ()*10); If (num<=5){resolve(num); } else{reject(' numbers are too large '); }}, 2000); }); p.then((data) => { console.log('resolved',data); },(err) => { console.log('rejected',err); });Copy the code

The use of the catch

We know that a Promise object has a catch method as well as a then method, so what does that do? This, like the second argument to THEN, specifies the reject callback. Here’s how it works:

p.then((data) => {
    console.log('resolved',data);
}).catch((err) => {
    console.log('rejected',err);
})
Copy the code

The effect is the same as in the second argument to then. However, it also serves another purpose: if an exception is thrown when the resolve callback (the first argument to then above) is executed, it does not trap the JS, but instead goes into the catch method. Take a look at the following code:

p.then((data) => { console.log('resolved',data); console.log(somedata); // SomeData undefined}). Catch ((err) => {console.log('rejected',err); });Copy the code

Problem sets to test