This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

What is a Promise?

Promise is a native constructor provided by ES6, which we can print to look at:

ƒ Promise() {[native code]} console.log(typeof Promise) FunctionCopy the code

As you can see, a Promise is a constructor, with all, Reject, and resolve methods, and then, catch, and other methods on the prototype. Create its object with the new keyword and the Promise constructor. This function takes two function arguments. When the asynchrony succeeds, the first function (resolve) is called and returns a value representing success. When it fails, the second function (Reject) is called and returns the reason for the failure.

A simple example
Const myFirstPromise = new Promise((resolve, reject) => {setTimeout(() => {math.random () > 0.5? resolve('success') : reject('fail'); }, 1000); }); console.log(myFirstPromise); // Promise {<pending>} myFirstPromise.then((result) => { console.log(result); }, (err) => { console.log(err); });Copy the code

A Promise must be in one of the following states:

  • Pending: An initial state that has neither been completed nor rejected.
  • This is a big pity: this will be fulfilled successfully.
  • Rejected: Indicates that the operation fails.

The then() method returns a Promise that takes at most two arguments: a callback to the Promise’s success and failure.

The first parameter (ondepressing) : This function will be called when the state of the Promise is fulfilled, and the function has one parameter, which is the final result of completion. If the argument is not a function, it is internally replaced with (x) => x, the function that returns the Promise final result as-is.

The second argument (onRejected) : This function is called when the state of the Promise is Rejected. This function takes one argument, the reason for the rejection. If the argument is not a function, it is internally replaced with a “Thrower” function (it throws an error it received as argument).

Myfirstpromise.then ((result) => {// When Promise is fulfilled console.log(result); }). Catch ((reason) => {console.log(reason); });Copy the code

The catch() method returns a Promise and handles the rejection. It behaves the same as calling THEN (undefined, onRejected).

Catch () takes an argument (the callback function) :

Function called when a Promise is rejected. This function takes one argument, reason(the reason of rejected)

This parameter is also rejected if it is not a function. This is consistent with the then() method where the second argument is not a function.

myFirstPromise.finally(() => {

});
Copy the code

The finally() method executes the callback function at the end of the Promise, whether the result is pity or Rejected. This avoids situations where the same statement needs to be written once in both then() and catch().

A finally() method might be what you need if you want to do something after a Promise has been executed, no matter what the result.

The callback function of the finally() method does not accept any arguments, which means there is no way to know whether the Promise state is fulfilled or rejected. This shows that finally is only used when the result is to be executed regardless of the final result, and that promises cannot be relied on to execute the result.

The finally() method always returns the original Promise object value when no exception is thrown itself; If an exception is thrown, the exception’s Promise object is returned.

More about Promise>>>

What is the meaning of promises?

We all know that Promise() execution is synchronous, while then() execution is asynchronous. Why?

Why is Promise() execution synchronous, but then() execution asynchronous? I just want to make “then” synchronous?

So let’s take a look at an Ajax sample test, using jquery.

data.json [ { "id": 1, "name": "zhangsan" }, { "id": 2, "name": "lisi" }, { "id": 3, "name": "wangwu" }, { "id": 7, "name": "LPieces"}] index.js "http://localhost:3000/data.json", success (data) { console.log(data.map(item=>item.name)); }}); console.log("My name is LPieces.");Copy the code

Running results:

In the above code, $.ajax() is asynchronous, and js execution is synchronous from top to bottom. When the asynchronous request does not come back, console.log() will print it. So now I want to pull the operation in SUCCESS out of the outer layer how do I do that? Look at the following code:

/ / asynchronous procedure const data = $. Ajax ({url: "http://localhost:3000/data.json", async: false / / synchronization}); console.log(data.responseJSON.map(item=>item.name)); console.log("My name is LPieces.");Copy the code

Running results:

When I set async: False The ajax on top is synchronized with the print on the bottom. Although it does what I want, the printed My name is LPieces and it waits for the ajax on the top to finish printing, which blocks all the code below. With that in mind, here’s how Promise helped me solve this problem:

const p = new Promise((resolve, reject) => {
    $.ajax({
        url: 'http://localhost:3000/data.json',
        success (data) {
            resolve(data);
        }
    })
})
p.then(res => {
    console.log(res.map(item=>item.name));
})
console.log("My name is LPieces.");
Copy the code

Running results:

If Promise() is executed synchronously, then() is executed asynchronously. If Promise() is executed synchronously, then() is executed asynchronously. If Promise() is executed synchronously, then() is executed asynchronously. Why write a Promise wrapped around Ajax?

Does Promise exist to solve callback hell?

The best way to solve callback hell is a combination of Promise + async awiat, for example:

Function getData(){return new Promise((resolve, reject) => {$.ajax({url: 'http://localhost:3000/data.json', success (data) { resolve(data); } }) }) } async function doSth(){ try{ const data = await getData(); console.log(data.map(item=>item.name)); console.log("My name is LPieces."); }catch(err){ console.log(err); } } doSth(); console.log("My name is LPieces.");Copy the code

Running results:

DoSth () and the following print are synchronized execution relationships. Async requests are handled in doSth(), and if you need to await the result of the previous request, just await it all the way.

Promises exist to synchronize solutions to asynchronous problems