To summarize the promise ES6

Basic Usage

promise has three states: pending (in progress), Fulfilled (has succeeded) and Rejected (has failed), Promise constructor takes a function as a parameter, two parameters are the function resolve and reject, which function will resolve pending to state fulfilled, reject function to be rejected pending state status upon change irreversibly. Parameter of the function of these two functions will be passed to the callback function

const promise = new Promise(function(resolve, reject) {
        // ... some code

        IF (/ * * asynchronous operation success /) {
            resolve(value);
        } else {
            reject(error);
        }
    });
    promise.then((value)=>{ 
        console.log(value)
    },(error)=>{
        console.log(error)
    })

 

then method

After Promise instance generation can be specified with each callback method then resolved state and rejected states, a first state is a pending-> fulfilled callback, the second is pending-> resolved callback.
Why then can be chained to call it? The reason is that the object is a promise then returned by the method, so the back can continue to use then () method.
Where there is a need to pay attention, focus on understanding the following sentence:
. Values returned from the callback onRejected Functions The onFulfilled or wrapped in Will Automatically BE A Promise resolved
value the then () function returns two parameters will automatically packaged into It has been resolved in a promise. (Meaning at .then or return a value in .catch out, it will be packaged in the form resolve (value) or pass behind .then .catch callback may return directly to a new target Promise, but this different methods can be controlled in this state to be about to return out of Promise resolve () or Reject ())


Code 1:

$http({
            method: 'GET',
            url: 'https://www.runoob.com/try/angularjs/data/sites.php1'
        }).then(function successCallback(data_1) {
            $scope.res = data_1;
            $scope.names = data_1.data.sites;
            return data_1;
        },function (err_1) {
            console.log("err_1",err_1);
            return err_1;
        }).then(function (data_2) {
            console.log("data_2", data_2)
        },function (err_2) {
            console.log("err_2---->",err_2);
        }).catch(function (reason) {
            console.log("err------->",reason);
        });

 

Note: $ http returns a promise object.

The results are as follows:
image description

Resolved> success callback function (why), then the reason is the callback function, whether it is success or failure callback callback, the value of their return will be packaged into a promise of object - a network request 404> failed callback method err_1 processing function, which will be passed to the next successful callback method then go inside.
Code 2:

Promise.resolve()
        .then(() => {
            return new Error('error!!!')
        })
        .then((res) => {
            console.log('then: ', res)
        })
        .catch((err) => {
            console.log('catch: ', err)
        })

 

The results are:
then: Error: error!!!
at Promise.resolve.then (...)
at ...

 

The reason is: .then or .catch the object does not return an error throw an error, but by resolved handled, it will not be .catch subsequent capture, need to change one of:

1.return Promise.reject(new Error('error!!!'))
2.throw new Error('error!!!')

 

catch method

Promise.prototype.catch is .then (null, rejection) syntactic sugar, to specify a callback function when an error occurs.
None of the methods 1.then second callback failure, when the reject, will enter the catch method; if then there is a second method fails
callback, the latter will enter the reject function, without going into catch method.

$http({
            method: 'GET',
            url: 'https://www.runoob.com/try/angularjs/data/sites.php'
        }).then(function successCallback(data_1) {
            $scope.res = data_1;
            $scope.names = data_1.data.sites;
            return data_1;
        },function (err_1) {
            console.log("err_1",err_1);
            return err_1;
        }).catch(function (reason) {
            console.log("err------->",reason);
        });

 

result:
image description

If not then there is a second callback, it will enter the catch method.
Small question: catch methods return a value in its success callback behind .then () will receive it in? The answer is yes, the catch is made without success to see the back .then (), whose return value will be resolved out.
Note: Do not define Reject state in which the callback function then the method (i.e., then the second parameter), always use a catch method. The second reason is that the wording can then capture the previous method of execution errors, but also closer to synchronize the wording (try / catch)

// bad
promise
  .then(function(data) {
    // success, marking 1. If an error is thrown in the code here, then this failure callback function is to capture visible.
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });

 

That is: If the "Mark 1" out of code throws an error, the latter failed callback function is to capture the invisible (only a promise on catching errors thrown objects themselves which are then captured in the invisible) , but only by the next then failed callback function (ie, catch) to capture.
example:

Promise.resolve()
        .then(function success (res) {
            throw new Error('error')
        }, function fail1 (e) {
            console.error('fail1: ', e)
        })
        .catch(function fail2 (e) {
            console.error('fail2: ', e)
        })

 

result:

fail2: Error: error
at success (...)
at ...

 

.then may receive two parameters, the first one is the function of processing is successful, the second process is a function of the error. .catch is simple wording .then the second argument, but they use a caveat: .then second error handling function can not catch the error function of the first successful treatment of thrown, and follow-up. the catch errors before you can capture
the following code can be:

Promise.resolve()
        .then(function success1 (res) {
            throw new Error('error')
        }, function fail1 (e) {
            console.error('fail1: ', e)
        })
        .then(function success2 (res) {
        }, function fail2 (e) {
            console.error('fail2: ', e)
        })

Guess you like

Origin www.cnblogs.com/itgezhu/p/12171825.html
Recommended