JavaScript - Asynchronous Programming

Since js is single-threaded, asynchronous execution is usually used for some time-consuming operations.

Commonly used asynchronous execution methods:

1. Callback function

If the following two functions are executed sequentially, fn1 is a time-consuming operation.

fn1(){};
fn2(){};

 

This is to consider executing fn2 as the callback function of fn1

fn1(callback){
  setTimeout(function(){
     //fn1 task
     callback();
  },1000)
}
fn1(fn2);

 Pros: Simple, easy to understand.

 Disadvantages: It is not conducive to the reading and maintenance of the code, the direct coupling of each part is high, the process is not clear and intuitive, and each task can only be bound to one callback function.

 2. Event monitoring

fn1.on('done',fn2);

 

    When fn1 executes the done event fn2 executes.

function fn1(){
  setTimeout(function(){
    //fn1 task
    fn1.trigger('done');
  },1000)
}

    fn1.trigger('done') indicates that the done event is triggered after the execution of the fn1 task is completed, and the execution of the fn2 task starts

    Advantages: simple and easy to understand, multiple events can be bound, and multiple callback functions can be specified for each event, which is conducive to decoupling and easy to achieve modularization.

    Disadvantages: The entire program has to become event-driven, and the running process is not clear enough.

 3. Publish/Subscribe (Observer Pattern)

We assume that there is a signal center, and when a task is executed, it will publish a signal to the signal center, and other tasks can subscribe to this signal to the signal center, so as to know when their tasks are executed.

 

Summary: This mode is similar to the event monitoring mode, but better than the latter, because we can use the message center to know how many signals exist and how many subscribers each signal has, so as to monitor the operation of the program.

 

 4,promise

Promise is a specification proposed by the CommonJS working group to provide a unified interface for asynchronous programming.

The idea of ​​promise implementation is that each asynchronous task will return a promise object, which has a then method that allows specifying a callback function, as follows:

fn1().then(fn2);

 

Implementation based on jquery

function fn1(){
   var dtd=$.Deferred();
   setTimeout(function(){
      //fn1 task
      dtd.resolve();
   },1000);
   return dtd.promise;
}

Advantages: Support chain writing (fn1().then(fn2).then(fn3)), and the task process is more intuitive and clear.

Disadvantages: difficult to implement and understand.

 

Reference: http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326124456&siteId=291194637