Front-end Asynchronous Solution-3 (Promise)

Posted by philip@hux.co.za on Sun, 12 May 2019 07:51:26 +0200

I haven't written for a few days. I've been learning Promise and generator intermittently these days. Today I can finally solve the asynchronous problem by combining the two things. Today I would like to share with you the usage of promise and the handling of asynchrony.
As usual, let's simulate a Promise first.

//Cough, that's how it works.
let MyPromise = Promise;

I'm kidding. I've been watching Promise for two days, but I still don't understand it. So I'll put Promise's code implementation on the shelf for the time being, and I'll start a new share when I fully understand it. I would like to recommend a few blogs that I think are better implemented by Promise. If you want to learn, you can go there to see them first. Of course, after I update them, you will come and give me some praise.
Understanding Promise Objects thoroughly - Implementing one's own Promise with es5 grammar The es5 grammar used in this article can be used by students who are not familiar with es6.
Promise Implementation Principle (with Source Code) This article is used for class es, so we need to know something about es6, which is also a good article.

Next, let me introduce some of the most commonly used parts of Promise:

  1. First, the simplest use of only one Promise object is introduced.

    //Promise() receives a function and, while creating the Promise object, the received function is executed immediately.
    var promise = new Promise(function (resolve, reject) {
      //resolve is used to receive successful returns, reject is used to receive failed returns
      setTimeout(function () {
        //Here we generate a random number and then judge whether the asynchronization is successful or not based on the size of the random number.
        let num = Math.random();
        if (num  > 0.8) {
          //Reasons for Failure in Receiving
          console.log("reject")
          reject(num + "Greater than 0.8,This asynchronous operation failed")
        } else {
          //Receiving Successful Data
          console.log("resolve")
          resolve(num + "Less than 0.8,This asynchronous operation succeeded")
        }
      }, 100)
    });
    console.log("One Promise Object generation");
    //The. then() method of the Promise object receives two callbacks, the first is a successful callback and the second is a failed callback.
    //These callbacks are called after the resolve or reject functions above take effect.
    promise.then(function (data) {
      //This function takes effect when the resolve function above is called, where data is the value received in the resolution () above.
      console.log(data)
    }, function (err) {
      /// This function takes effect when the reject function above is called, where err is the value received in reject().
      console.error(err)
    });
    console.log("promise Of.then Method is called")

    You can call up the console by pressing F12 and run this code several times. See what happens.
    After several more runs, you should see these two kinds of results:


    Here you can see that the results of success or failure are printed after the timer is executed. This way of writing can help us to implement simple asynchronous programming.

  2. Next, we introduce the use of multiple Promise objects at the same time. First, we introduce the most common method of. then() chain invocation.

     //Used to quickly generate a Promise object, receive a log list, whether successful or unsuccessful, add a log to the log list
     function promise(log) {
       return new Promise(function (resolve, reject) {
         setTimeout(function () {
           log = log || [];
           //As in the previous example, use random numbers to randomly fail and succeed
           let num = Math.random();
           if (num > 0.5) {
             log.push(num + "Greater than 0.5,This asynchronous operation failed");
             reject(log)
           } else {
             log.push(num + "Less than 0.5,This asynchronous operation succeeded");
             resolve(log)
           }
         }, 100)
       })
     }

    The Promise object is returned in. then().

    var promise1 = promise();
    //The promise1.then() method returns a Promise object
    //If we have a Promise object returned in the. then() method!!!!! Callback method!!!! If there is a Promise object returned, the object will be!!!!. then() method!!!!! Return!
    
    //Look first at how the Promise object is returned
    promise1.then(function (data) {
      console.log(data);
      return promise(data)
    }, function (err) {
      console.error(err);
      return promise(err)
    }).then(function (data) {
      console.log(data)
    }, function (err) {
      console.error(err)
    });

    There are four results when this code runs:
    Successful on both occasions

    Both failures

    First failure, second success

    First success, second failure

    In this way, we can write our asynchronous code in a clearer way. Especially when multiple asynchronous operations are nested, they can be implemented by chain call. then(), which makes the code more logical.
    I just finished looking at the scenario where I returned the Promise object, and then I'll look at the scenario where I didn't return the Promise object.

    //If we don't return the Promise object, then() wraps what we return as a Promise object (without returning, we return undefined).
    //It can be equivalent to writing return new Promise ((resolution, reject) => {resolve (/* the original return value */)})
    promise1.then(function (data) {
      console.log(data);
      return data;
    }, function (err) {
      console.error(err);
      return err;
    }).then(function (data) {
      console.log(data)
    }, function (err) {
      //This is never triggered because the last. then() returned a new Promise ((resolution, reject) => {resolve (/* the original return value */)}.
      //The reject method of the returned Promise object will never be triggered, so it will never be triggered here.
      console.error(err)
    });

    The explanations are all written in the comments. Next, I will paste a running chart. This code will run the following two kinds of results:

  3. All requests need to be returned before an action can be executed

    //Modify promise so that it can receive a timer wait time parameter
    function promise(log, time) {
      return new Promise(function (resolve, reject) {
        setTimeout(function () {
          log = log || [];
          //As in the previous example, use random numbers to randomly fail and succeed
          let num = Math.random();
          if (num > 0.5) {
            log.push("Waiting time" + time + "," + num + "Greater than 0.5,This asynchronous operation failed");
            console.error(log);
            reject(log)
          } else {
            log.push("Waiting time" + time + "," + num + "Less than 0.5,This asynchronous operation succeeded");
            console.log(log);
            resolve(log)
          }
        }, time)
      })
    }
    //Promise.all() can receive an array of Promise objects and return a Promise object.
    //The Promise object executes a successful callback after all Promises in the array return successfully, and a failed callback immediately after any Promise fails.
    var promise1 = promise(null, 10), promise2 = promise(null, 100),
      promise3 = Promise.all([promise1, promise2]);
    promise3.then((data) => {
      //Here the data is promise1, and the array of returned values of promise2
      console.log("promise3", data)
    }, (err, err2) => {
      //Wrong information
      console.error("promise3", err)
    });

    There are four possible outcomes for this code
    If it succeeds both times

    If both are successful, promise3 performs a successful callback, and the data in the callback is an array of returned values of promise1 and promise2 (in the same order as in. all()).



    If any promise fails, promise 3 immediately performs a failed callback, and the err or in the callback is the value returned by the failed promise in reject.

As I write here, I think some of the commonly used uses of Promise have been exhausted. For more detailed instructions on Promise, please refer to them. Explanation of promise in MDN

Topics: Javascript less Programming