By Jing Zhaoxia

Source public number/notes on light and shadow of the morning glow

ID / zhaoxiajingjing

Sunday, Sunday, Sunday, Sunday, Sunday, Sunday, Sunday, Sunday, Sunday, Sunday, Sunday, Sunday


The method of Promise

After writing the principle of a Promise by hand, it’s much easier to understand the Promise approach.

Okay, let’s just go to code ~

Catch method

  • use

The catch method is the syntactic sugar of the THEN method and only accepts data from the Rejected state.

1let p = new Promise((resolve, reject) = > {

2    reject('It's my fault to fall in love with you O (╥﹏╥) O');

3});

4

5p.then(data= > {

6    console.log(data, 'data');

7}).catch(err= > {

8    console.log(err, 'err');

9});

Copy the code
  • implementation

Catch is the syntactic sugar of the then method

1Promise.prototype.catch = function(callback){

2    return this.then(null, callback);

3};

Copy the code

The finally method

  • use

The finally method is going to get here anyway.

In the finally method, data in either a success or a failure state is not accepted, and the value passes through to the next one.

It’s a good place to put some of the logic of both the success state and the failure state.

 1let p = new Promise((resolve, reject) = > {

2    reject('It's my fault to fall in love with you O (╥﹏╥) O');

3});

4

5p.then(data= > {

6    console.log(data, 'data');

7}).finally(data= > {

8    console.log(data, 'finally');

9}).catch(err= > {

10    console.log(err, 'err');

11});

Copy the code
  • implementation
  1. In the finally method, the value just goes through the motions
  2. If the callback contains a Promise, wait for its result.
 1Promise.resolve = function (value){

2    return new Promise((resolve, reject) = > {

3        resolve(value);

4    });

5};

6Promise.prototype.finally = function (callback){

7    return this.then(data= > {

8        return Promise.resolve(callback()).then((a)= > data);

9    }, err => {

10        return Promise.resolve(callback()).then((a)= > {throw err});

11    });

12};

Copy the code