Tips for using promise

Time:2021-2-26

1、 About promise

Promise is a solution of asynchronous programmingIt is more reasonable and powerful than traditional solutions (callback functions and events). It was first proposed and implemented by the community. ES6 has written it into the language standard, unified the usage, and provided the native languagePromiseObject.

so-calledPromiseIn short, it is a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, promise is an object from which messages of asynchronous operations can be obtained. Promise provides a unified API, and all kinds of asynchronous operations can be handled in the same way.

It represents an asynchronous operation. There are three states:

  • pendingIn progress: initial state, initial state, incomplete or rejected.
  • resolved(completed): indicates that the operation completed successfully. also calledfulfilled
  • rejected(failed): indicates that the operation failed.

YesPromiseThe asynchronous operation can be expressed as the process of synchronous operation, but it also has the following advantagesshortcoming

  • Once created, it is executed immediately and cannot be cancelled halfway.
  • If the callback function is not set,PromiseAn internal error is not reflected externally.
  • When inPendingIt is impossible to know which stage (just started or about to finish) the current progress has reached.

2、 Application examples

1. Create promise

var promise = new Promise(
    /* executor */ 
    function(resolve, reject){
        ...
    }
);

The executor function is implemented immediately by Promise, passing resolve and reject functions. (before invoking the actuator or even returning the object created before the Promise constructor)

InexecutorInternally, promise may have the following state changes:

1. Resolve is called, and the promise changes from pending to resolved, which means that the promise is resolved successfully

​ 2.rejectWhen called, the project changes from pending to rejected, which means that the value of the project cannot be used for subsequent processing, that is, it is rejected

be careful:

  1. If inexecutor If any exception is thrown during the execution of the method, the project will be rejected immediately (that is, the reject method will be called),executor The return value of is also ignored.
  2. If a promise object is inresolvedorrejectedInstead of the pending state, it can also be called thesettledStatus.

2. Handle promise instance

  • then: after the promise instance is generated, you can use thethenMethods are specified separatelyResolvedStatus andRejectThe callback function of the state.

    promise.then(function(value) {
      //Called when the success state is resolved
    }, function(error) {  
      //Called when failure state is reject
    });

thenMethod can take two callback functions as parameters.

The first callback function: when the promise state becomesresolvedIs called when. Its parameter is the return value of the resolve method of promise.

The second callback function: when the promise state becomesrejectedIs called when. Its parameter is the return value of the reject method of project. It is an optional parameter.

  • catchPromise.prototype.catchThe method is.then(null, rejection)Alias forSpecifies the callback function when an error occurs

    promise.then(function(posts) {
      // ...
    }).catch(function(error) {
      console.log ('error! ', error); // handle the errors that occur when promise and the previous callback function are running
    });
  • Extension:

    • Promise.prototype.thenAndPromise.prototype.catchMethod, so they can be chained.But the new promise instance generated by the function return value is returned, not the original promise instance

    Tips for using promise

Note:

  1. The error of the promise object is “bubbling” and is passed back until it is caught. In other words, mistakes are always followed by the next onecatchStatement capture.

3. Package multiple promise instances into a new promise instance

  • Promise.all(iterable): returns “project” when all “projects” in the iteratable parameters have been completed, or the first “project” passed fails.

    var p = Promise.all([p1, p2, p3]);
    • When the states of P1, P2 and P3 are all negativeresolvedThe state of P isresolved
    • When any one of P1, P2 or P3 isrejectedpThe state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of being in the state of beingrejectedAnd the first one isrejectWill be passed to thepThe callback function of.

Specific examples are as follows:

  • Case 1:All successful cases

    Promise.all([Promise.resolve('foo'),Promise.resolve('bar'),Promise.resolve('test')])
      .then(function(result){
                console.log (result); // the result is: [foo, bar, test]. That is, an array of all return values.
             })
       .catch(function(error) {
               console.log ('error '); // will not be executed
       });
  • Case 2:Total or partial failure

    Promise.all([Promise.resolve('foo'),Promise.reject('barError'),Promise.reject('testError')])
       .then(function(result){
                console.log (result); // successful callbacks will not be executed
             })
       .catch(function(error) {
               console.log (error); // the result is barerror or testerror. That is, the first value to be rejected.
       });

3、 Common mistakes in use

  • Forget to add. Catch ()

Generally, promise has the following two processing methods:

//Bad writing-------------
promise.then(function(data) {
    // success
  }, function (ERR) {// only handle errors that occur when promise is running. Unable to handle error in callback
    // error
  });

//Good writing------------
promise.then(function(data) {
    // success
}). Catch (function (ERR) {// handle the error of promise and previous callback function
    // error 
});

Because errors thrown by promise are not passed to the outer code. When using the first method without catch, the error of successful callback cannot be handled. So a better way is to use it all the timecatchmethod.

  • Return is not used in then or catch functions

Here is a common mistake when using promise:

//------------Bad writing------------------
promise.then(function () {
  getUserInfo(userId);
}).then(function () {
  //You may want to use user information in this callback, but you may find that it doesn't exist at all
});

The above error occurs because of insufficient understanding of promise return and chained call.

Every promise will give you a then () method (or catch, they are just then (null )The grammar of sugar. Here we look inside the then () method

promise.then(function () {
  return getUserInfo(userId);
}).then(function (userInfo) {
   HadleUser(userInfo);
}).catch(function(error) {
   console.log(error);
});

There are three things you can do in callbacks:

    1. Return to another promise

    IfgetUserInfoReturns a promise, thenHadleUserIt will be executed after the promise becomes resolved, with the return of the promise as the input parameter.

    1. Returns a synchronized value (or undefined)

    getUserInfoIf a synchronous value is returned, the modified value will be packaged as a resolved promise,HadleUserWill be executed immediately with getUserInfo as the input parameter.

    1. A synchronization error was thrown

    getUserInfoIf a synchronization error is returned, the error will be packaged as a project in the rejected state and finally caught in catch. hereHadleUserWill not be executed.

    • Promises lost

    What do you think the following code will print out?

    Promise.resolve('foo').then(Promise.resolve('bar')).then(function (result) {
      console.log(result);
    });

    If you think the bar is printed, you’re wrong. It actually prints foo.

    as a result ofWhen you pass a non function (such as a promise) value to then (), it will actually be interpreted as then (null), which will cause the previous promise result to be lost.

    4、 Best practice summary

    1. thenForever in the methodreturnOrthrow
    2. IfpromiseThere may be errors in the chain, so be sure to add themcatch
    3. Always transfer function tothenMethods
    4. Don’t take itpromiseWrite nested

    Reference link:

    Promise -JavaScript | MDN

    Promises is cool, but many people use it without understanding it

    Promise object

    Recommended Today

    Third party calls wechat payment interface

    Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]