Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Asynchronous programming in Javascript

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article focuses on "how to achieve asynchronous programming in Javascript", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to realize asynchronous programming in Javascript"!

What are the methods of Javascript asynchronous programming

The advantage of this model is that it is relatively simple to implement and the execution environment is relatively simple; the downside is that as long as there is a task that takes a long time, the following tasks must wait in line, which will delay the execution of the whole program. Common browsers are unresponsive (fake death), often because a piece of Javascript code runs for a long time (such as an endless loop), resulting in the entire page stuck in this place, other tasks can not be performed.

To solve this problem, the Javascript language divides the execution mode of tasks into two modes: synchronous (Synchronous) and asynchronous (Asynchronous).

The "synchronous mode" is the mode of the previous paragraph, and the latter task waits for the end of the previous task before it is executed. The execution order of the program is consistent with the order of the tasks and synchronized. "Asynchronous mode" is completely different, each task has one or more callback functions (callback), after the end of the previous task, not the execution of the next task, but the implementation of the callback function, the latter task is executed without waiting for the end of the previous task, so the execution order of the program and the order of the tasks are inconsistent and asynchronous.

Asynchronous mode is very important. On the browser side, long-time operations should be performed asynchronously to prevent the browser from losing its response. the best example is the Ajax operation. On the server side, "asynchronous mode" is even the only mode, because the execution environment is single-threaded, and if all http requests are allowed to be executed synchronously, server performance degrades sharply and quickly becomes unresponsive.

1. Callback function

This is the most basic method of asynchronous programming.

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

F1 ()

F2 ()

If F1 is a time-consuming task, consider rewriting F1 to write F1 as a callback function of F1.

Functionf1 (callback) {

SetTimeout (function () {

/ / task code of F1

Callback ()

}, 1000)

}

Executing the code looks like this:

F1 (f2)

In this way, we turn synchronous operations into asynchronous operations. F1 does not block the running of the program, which is equivalent to executing the main logic of the program first, delaying the execution of time-consuming operations.

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

II. Event monitoring

Another way of thinking is to adopt the event-driven mode. The execution of tasks does not depend on the order of the code, but on whether an event occurs.

Let's take F1 and f2 as examples. First, bind an event to F1 (the jQuery 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:

Functionf1 () {

SetTimeout (function () {

/ / task code of F1

F1.trigger ('done')

}, 1000)

}

F1.trigger ('done') indicates that the done event is triggered immediately after the execution is completed, thus starting the execution of f2.

The advantage of this approach is that it is easy to understand, can bind multiple events, each event can specify multiple callback functions, and can be "Decoupling", which is conducive to modularization. The disadvantage is that the whole program will become event-driven, and the running process will become very unclear.

What are the methods of Javascript asynchronous programming

III. Publish / subscribe

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

We assume that there is a "signal center". When a task is completed, a signal is "publish" to the signal center, and other tasks can "subscribe" the signal from the signal center to know when they can start execution. This is called the publish / subscribe pattern (publish-subscribepattern), also known as the Observer pattern (observerpattern).

There are several implementations of this pattern, and the following is BenAlman's TinyPub/Sub, which is a plug-in for jQuery.

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

JQuery.subscribe ("done", f2)

Then, F1 makes the following rewriting:

Functionf1 () {

SetTimeout (function () {

/ / task code of F1

JQuery.publish ("done")

}, 1000)

}

JQuery.publish ("done") means that after F1 execution is completed, a "done" signal is issued to the "signal center" jQuery, thus triggering the execution of f2.

In addition, f2 can also unsubscribe (unsubscribe) after completion of execution.

JQuery.unsubscribe ("done", f2)

The nature of this method is similar to "event monitoring", but is significantly better than the latter. Because we can monitor the operation of the program by looking at the "message center" to find out how many signals exist and how many subscribers there are for each signal.

4. Promises object

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

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

F1 (). Then (f2)

F1 needs to be rewritten as follows (the implementation of jQuery is used here):

Functionf1 () {

Vardfd=$.Deferred ()

SetTimeout (function () {

/ / task code of F1

Dfd.resolve ()

}, 500)

Returndfd.promise

}

The advantage of writing in this way is that the callback function has become chained writing, the flow of the program can be seen clearly, and there are a set of supporting methods that can achieve many powerful functions.

For example, specify multiple callback functions:

F1 (). Then (f2). Then (f3)

For example, specify the callback function when an error occurs:

F1 (). Then (f2). Fail (f3)

Moreover, it has an advantage 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.

At this point, I believe you have a deeper understanding of "how to achieve asynchronous programming in Javascript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report