4 Methods of Asynchronous Programming in Javascript

1. Callback function

This is the most basic approach to asynchronous programming.

Suppose there are two functions f1 and f2, the latter waiting for the execution result of the former.

  f1 ();

  f2();

If f1 is a time-consuming task, consider rewriting f1 and writing f2 as a callback function of f1.

  function f1(callback){

    setTimeout(function () {

      // task code for f1

      callback();

    }, 1000);

  }

The execution code becomes as follows:

  f1(f2);

In this way, we turn the synchronous operation into an asynchronous operation, and f1 will not block the operation of the program, which is equivalent to executing the main logic of the program first, and delaying the execution of time-consuming operations.

The advantage of the callback function is that it is simple, easy to understand and deploy, but the disadvantage is that it is not conducive to the reading and maintenance of the code, and the various parts are highly coupled (Coupling), the process will be very chaotic, and only one callback function can be specified for each task.

2. Event monitoring

Another idea is to use an event-driven model. The execution of tasks does not depend on the order of the code, but on whether an event occurs.

Take f1 and f2 as an example. First, bind an event to f1 (the jQuery way of writing is used here ).

  f1.on('done', f2);

The above line of code means that when a done event occurs in f1, f2 is executed. Then, rewrite f1:

  function f1(){

    setTimeout(function () {

      // task code for f1

      f1.trigger('done');

    }, 1000);

  }

f1.trigger('done') means that after the execution is completed, the done event is triggered immediately, thereby starting to execute f2.

The advantage of this method is that it is easier to understand, multiple events can be bound, multiple callback functions can be specified for each event, and it can be "decoupled" (Decoupling), which is conducive to the realization of modularization . The disadvantage is that the entire program has to become event-driven, and the running process will become very unclear.

3. Publish/Subscribe

The "event" in the previous section can be completely understood as a "signal".

We assume that there is a "signal center", and when a task is completed, it "publishes" a signal to the signal center, and other tasks can "subscribe" to the signal center to know when they can Begin execution. This is called "publish/subscribe pattern" (publish-subscribe pattern), also known as "observer pattern" (observer pattern).

There are multiple implementations of this pattern, the following is Tiny Pub/Sub by Ben Alman , a plugin for jQuery.

First, f2 subscribes the "done" signal to the "signal center" jQuery.

  jQuery.subscribe("done", f2);

Then, f1 is rewritten as follows:

  function f1(){

    setTimeout(function () {

      // task code for f1

      jQuery.publish("done");

    }, 1000);

  }

jQuery.publish("done") means that after the execution of f1 is completed, the "done" signal is published to the "signal center" jQuery, thereby triggering the execution of f2.

In addition, after f2 finishes executing, you can also unsubscribe.

  jQuery.unsubscribe("done", f2);

This approach is similar in nature to "event listeners", but is significantly better than the latter. Because we can monitor the operation of the program by looking at the "message center" to see how many signals exist and how many subscribers each signal has.

Fourth, the Promises object

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

Simply put, the idea is that each asynchronous task returns a Promise object that has a then method that allows specifying a callback function. For example, the callback function f2 of f1 can be written as:

  f1().then(f2);

f1 should be rewritten as follows (the jQuery implementation is used here ):

  function f1(){

    var dfd = $.Deferred();

    setTimeout(function () {

      // task code for f1

      dfd.resolve();

    }, 500);

    return dfd.promise;

  }

The advantage of writing in this way is that the callback function becomes a chained writing method, the flow of the program can be clearly seen, and there is a complete set of supporting methods , which can realize many powerful functions.

For example, to specify multiple callback functions:

  f1().then(f2).then(f3);

For another example, specify a callback function when an error occurs:

  f1().then(f2).fail(f3);

Moreover, it has a benefit that none of the previous three methods have: if a task has been completed, and then add a callback function, the callback function will be executed immediately. So, you don't have to worry about missing an event or signal. The disadvantage of this method is that it is relatively difficult to write and understand.

5. Reference links

  * Asynchronous JS: Callbacks, Listeners, Control Flow Libs and Promises

(over)

Guess you like

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