JS asynchronism (promise)

Time:2021-6-15

JS asynchronous one (basic knowledge)
JS asynchronous events 2 (distributed events)
JS asynchronism (promise)
JS asynchronous 4 (HTML 5 web workers)
JS asynchronous 5 (asynchronous script loading)

Promise, deferred object

Foreplay

Let’s talk about the use of promise in jQuery and take a look at an example
Originally wrote a small animation, we may be like this

<script type="text/javascript"> 
$('.animateEle').animate({
  opacity:'.5'
}, 4000,function(){
  $('.animateEle2').animate({
    width:'100px'
  },2000,function(){
    $('.animateEle3').animate({
      height:'0'
    },2000);
  });
});
</script> 

But if we use the promise object, we can make the code easier to understand

<script type="text/javascript"> 
var animate1 = function() {
  return $('.animateEle1').animate({opacity:'.5'},4000).promise();
};
var animate2 = function() {
  return $('.animateEle2').animate({width:'100px'},2000).promise();
};
var animate3 = function(){
  return $('.animateEle3').animate({height:'0'},2000).promise();
};
$.when(animate1()).then(animate2).then(animate3);
</script>

After reading the above examples, I have a certain understanding of the function of promise. Let’s talk about the principle of promise

Promise object method

For DOM, animation, AJAX related methods, you can use promise method. Call the promise method and return the promise object. You can chain call the promise method.

For example, the $. Post $. Get $. Ajax method in jQuery actually calls the promise method by default, and then returns a promise object

There are three common methods of promise object: done, fail and then.

<script type="text/javascript"> 
$.get('/',{}).done(function(data){
    console.log('success');
}).fail(function(){
    console.log('fail');
});
</script>

There are too many interface methods in jQuery. Just like the early event method binding, live, delegate, bind are still on

Deferred object method

Deferred object, that is, the object created by using $. Deferred () method and $. When () method, can be understood as a special promise object of the upgraded version
Let’s take a look at an example

<script type="text/javascript"> 
  var  promisepbj = new $.Deferred();

     promisepbj.done(function() {
      console.log('haha,done');
    }).fail(function() {
      Console.log ('failed ');
    }).always(function(res) {
      Console.log ('I'm always executed ');
    });

    //Use resolve or reject to call the defferred object
    promisepobj.resolve();
    //promisepobj.reject();

The resolve method will trigger the callback execution of done, and the reject method will trigger the callback of fail. For the always method, the deferred object, whether resolve or reject, will trigger the callback of this method.

ES6 Promise

As mentioned above, many promise implementations of jQuery are different between $. Deferred and es2015, because the former does not conform to promises / A + specification. Promise object has become a standard in emcascript 2015. Now let’s talk about the ES6 native promise object that will soon become the mainstream trend. First of all, post a very detailed ES6 promise book, which basically includes all you know and don’t knowhttp://liubin.org/promises-book/#introduction

There are many articles that explain promise clearly. I think I can’t write as well as them, so I simply paste the article of Ruan Yifeng Dashenhttp://es6.ruanyifeng.com/#docs/promise
I’ll take a simplified version of it, with the shortest number of words to enter a door.

definition:

Promise is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future.
characteristic:

  1. There are three states: pending, resolved, and rejected.

  2. Once the state changes, it won’t change again. You can get this result at any time. There are only two possibilities for a project object to change its state: from pending to resolved and from pending to rejected. As long as these two things happen, the state solidifies

Basic Usage

<script type="text/javascript"> 
var promise = new Promise(function(resolve, reject) {
  // ... some code

  If (/ * asynchronous operation succeeded * /){
    resolve(value);
  } else {
    reject(error);
  }
});
</script>

The promise constructor takes a function as a parameter, and the two parameters of the function are resolve and reject.

  <script type="text/javascript"> 
function timeout(ms) {
  return new Promise((resolve, reject) => {
    setTimeout(resolve, ms, 'done');
  });
}

timeout(100).then((value) => {
  console.log(value);
});
</script>

In the above code, the timeout method returns an instance of promise, which represents the result that will occur after a period of time. After the specified time (MS parameter), the state of the promise instance changes to resolved, and the callback function bound to the then method will be triggered.

exception handling

Exception handling has always been a difficult problem in callback, and promise provides a very convenient catch method: in a call to promise, any part of a reject can be caught in the final catch

Promise.resolve().then(function(){
    return loadImage(img1);
}).then(function(){
    return loadImage(img2);
}).then(function(){
    return loadImage(img3);
}).catch(function(err){
    //Error handling
})

Basic API

Promise.resolve()
Promise.reject()
Promise.prototype.then()
Promise.prototype.catch()
Promise.all()
Promise.race()

Summary

A lot of specific usage can refer to Ruan Yifenghttp://es6.ruanyifeng.com/#docs/promiseIntroductory course, there is the e-book mentioned abovehttp://liubin.org/promises-book/#introduction