ES6 series promise

Time:2020-11-25

Video Explanation

What is the promise of ES6? It’s a promise. In order to solve JS callback hell. Promise gives me the experience is: at first, it is in a fog, and then the more you use it, the better you can use it. What does commitment mean today? For example, I promise to buy an iPhone if I lose weight successfully, and die if I lose weight ~, ha ha, but I don’t.

Basic grammar

new Promise((resolve, reject) => {
    // ...
});

The resolve and reject methods are provided by the JS engine and do not need to be written by individuals.

Three states of promise

  1. Pending (in progress). After the new promise() command is executed, the promise instance is in the pending state.
  2. The resolve method is executed inside promise. Promise instance is in fullfilled state and the state cannot be changed.
  3. Rejected (failed). The reject method is executed inside the project. The project instance is in the rejected state and cannot be changed.

Promise.prototype Methods then and catch

new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('hello resolve');
    }, 500);
})
.then(val => {
    console.log(val);// hello resolve
}, err => {
    console.error (ERR); // the statement is not executed
});

Then has at most two parameters. The first parameter is the callback function after resolve, and the second is the callback function after reject. Then can also receive only parameter one.

new Promise((resolve, reject) => {
   setTimeout(() => {
       reject('hello reject');
   }, 500);
})
.then(val => {
   console.log(val);
}, err => {
   console.error(err);// hello reject
});

In fact, catch is a short form of then function. When reject is executed, it can be received and processed by the callback function of catch.

new Promise((resolve, reject) => {
    setTimeout(() => {
        reject('hello reject');
    }, 500);
})
.catch(err => {
    console.log(err); // hello reject
});

On exception handling of promise object

If an error occurs inside promise, it will not be caught by the outer environment.

try {
    new Promise((resolve, reject) => {
        console.log(e);
    });
} catch(e) {
    console.log ('error is caught? ', e); // the statement was not executed
}

If there is an internal error in project, it will be rejected automatically.

new Promise((resolve, reject) => {
    console.log(e);
})
.catch(err => {
    console.log('error be rejected?', err);// error be rejected? ReferenceError: e is not defined
});

Let’s look at the chain call of promise

let p = new Promise((resolve, reject) => {
    resolve('i am resolved');
})
.then(val => {
    return val;
});
console.log(p);// Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

In then, the value of return becomes a promise object.

p.then(val => {
    console.log(val);// i am resolved
});

This also provides the basis for chaining calls.

The static method of promise all race resolve reject

all

The all static method receives an array of promise objects and returns a promise object. When all elements in the array are resolved, the result promise is resolved. If an object in the array is rejected, the result project object is rejected. I often use all method to process multiple Ajax requests to obtain the interface loading effect of data.

let isLoading = true;
let p1 = fetch(url1).then(json => {
    // ....
});
let p2 = fetch(url2).then(json => {
    // ...
});
let p3 = fetch(url3).then(json => {
    // ...
});
Promise.all([p1, p2, p3]).then(() => {
    isLoading = false;
});

race

Also receive an array, the result is a promise object. When the state of one promise object in the array changes, the result promise object of race method changes to the same state. The specific application scenario has not been encountered by the author. If anyone has met, please leave a message below, thank you very much.

resolve、reject

Static function Promise.resolve Return a successful promise object, static function Promise.reject Returns a promise object with a reject status.

refs

MDN Promise

[recommended development environment] cloud studio is an integrated development environment based on browser. It supports most programming languages, including HTML5, PHP, python, Java, ruby, C / C + +,. Net applet, etc., without downloading the installation program, it can switch the development environment with one click. Cloud Studio provides a complete linux environment, supports custom domain name pointing, dynamic computing resource adjustment, and can complete the development, compilation and deployment of various applications.