What are Promise objects?

Promise is a solution to asynchronous programming that is more powerful and convenient than traditional solutions (callbacks and events) (see below). Syntactically, a Promise is an object from which to get messages for asynchronous operations. The Promise object provides a uniform API, and various asynchronous operations can be handled in the same way.

What does Promise do?

The consensus answer is, solve callback hell. So what is callback hell? What are its disadvantages?

If we had to do four steps, one at a time, then traditionally we might do this:

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});
Copy the code

To get around this uncomfortable looking, even more uncomfortable writing, we might think of the chain notation:

var obj = {
    stepOne: function () {
        console.log('one');
        return this;
    },
    stepTwo: function () {
        console.log('two');
        return this;
    },
    stepThree: function () {
        console.log('three');
        return this;
    }
}

obj.stepOne().stepThree().stepTwo();
Copy the code

The core of this notation is that we return this every time. The benefits of this are:

  • Each operation is a separate function
  • It can be assembled, which means we can control the process of execution

What if we need something else? Such as:

  • It would be even better if the results of the previous step served as input for the next step
  • If something goes wrong I can catch it, even better
  • If only I could control the flow in the function….

That’s where our powerful Promise comes in

Basic usage

Let’s see how to use it first! Directly on the code:

const p1 = new Promise(function(resolve, reject) {// do some logic here // Call resolve if the asynchronous operation succeedsif (true) {
        resolve('success');
    } elseReject () reject() reject()'fail');
    }
})

p1.then((val) => {
    console.log(val); // success
}, (err) => {
    console.log(err)
})
Copy the code

We can see that a Promise is a constructor that generates a Promise instance that takes as an argument a function that takes two arguments, resolve and Reject (these are also two functions that are already provided by the JavaScript engine and don’t need to be deployed themselves).

We often process logic in this function, executing resolve (converting the state from “incomplete” to “complete”) if it succeeds and reject (converting the state from “incomplete” to “failed”) if it fails.

Three state

  • Pedding (not completed)
  • Resolved (complete)
  • Rejected (failure)

After the instance is generated, we can use the then method to specify the resolved and Rejected state callback functions. This code is equivalent to executing the first callback, but not the second.

If it fails, the second callback is executed when the state is reject, which prints ‘fail’. However, this is not recommended. We can write the second callback as a catch method.

const p1 = new Promise(function(resolve, reject) {// do some logic here // Call resolve if the asynchronous operation succeedsif (false) {
        resolve('success');
    } elseReject () reject() reject()'fail');
    }
})

p1.then((val) => {
    console.log(val);
}).catch((err) => {
    console.log(err); // fail
})
Copy the code

This is similar to try… catch… Is easier for us to understand. At this point we’ve actually solved the problem that went wrong and we can catch it.

Control the order in which code is executed

Using chained THEN, you can specify a set of callback functions that are called in order. In this case, the previous one might return another Promise object (that is, an asynchronous operation). This later Promise depends on the state of the previous Promise object.

const p1 = new Promise(function(resolve, reject) {
    console.log(1);
    setTimeout(function() {
        console.log(2);
        resolve();
    }, 1000);
})

const p2 = new Promise(function(resolve, reject) {
    console.log(3);
    resolve(p1);
})

p2.then(() => {
    console.log(4);
}).then(() => {
    console.log(5);
})
Copy the code

Note that P2’s resolve method takes P1 as an argument, meaning that p2’s execution depends on p1’s execution. When P2 is ready, p1 may not be ready, and then P2 has to wait for P1.

Another point to note is that the THEN method returns a new Promise instance (note, not the previous Promise instance), so you can use chained notation, where the then method is followed by another THEN method. In this way, we can achieve the above requirements!

A few important ways Promise works

Here’s a quick look at some of the methods we use on Promise objects.

Promise.all()

Directly on the code:

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

The promise. all method takes an array as an argument, and P1, P2, and p3 are all Promise instances. At this time, the states of P are p1, P2, p3. Now we use three lines (P1, P2 and P3) in series, and P is the last light bulb. If the light bulb needs to light up, all three of them must succeed, as long as one of them fails, then P’s state is rejected.

Promise.race()

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

This method also takes an array as an argument. The English word “race” means a race. The code above shows that whichever of P1, P2, or P3 wins (with the latest state change, either a failure or a success), then the state of P changes with it.

Promise.resolve()

What it does: Converts existing objects into Promise objects so we can call then methods, etc

const jsPromise = Promise.resolve($.ajax('/whatever.json'));
Copy the code

Promise.reject()

The promise.Reject (Reason) method also returns a Promise instance with a state of Rejected.

const p = Promise.reject('Wrong'); // const p = new Promise((resolve, reject) => reject('Wrong'))

p.then(null, function(s) { console.log(s) }); / / make a mistakeCopy the code

Reference: https://cnodejs.org/topic/560dbc826a1ed28204a1e7de

http://es6.ruanyifeng.com/#docs/promise