JavaScript Asynchronous Programming


Asynchronous concept

Asynchronous (async) is a concept opposite to synchronous (sync).

In the traditional single-threaded programming that we learn, the program runs synchronously (synchronization does not mean that all steps are running at the same time, but that the steps are executed in sequence in a control flow sequence). The asynchronous concept is a concept that does not guarantee synchronization, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence.

To understand it simply: Synchronous execution is performed in the order of your code, and asynchronous execution is not in the order of code. Asynchronous execution is more efficient.

The above is an explanation of the concept of asynchrony. Next, let's explain asynchrony in layman's terms: Asynchrony is to launch a child thread from the main thread to complete the task.

image.png

When to use asynchronous programming

In front-end programming (even the back-end is sometimes in the case), when we are dealing with some short and fast operations, such as calculating the result of 1 + 1, it can often be done in the main thread. As a thread, the main thread cannot accept multiple requests at the same time. Therefore, when an event is not over, the interface will not be able to process other requests.

Now there is a button, if we set its onclick event to an endless loop, then when the button is pressed, the entire web page will lose response.

In order to avoid this situation, we often use child threads to complete things that may take long enough to be noticed by the user, such as reading a large file or issuing a network request. Because the child thread is independent of the main thread, it will not affect the operation of the main thread even if it is blocked. But the child thread has a limitation: once it is launched, it will lose synchronization with the main thread. We cannot be sure of its end. If something needs to be processed after the end, such as processing information from the server, we cannot merge it into the main thread. In.

In order to solve this problem, asynchronous operation functions in JavaScript often implement the result processing of asynchronous tasks through callback functions.

Callback

A callback function is a function that tells it when we start an asynchronous task: what to do after you finish the task. In this way, the main thread hardly needs to care about the status of the asynchronous task, and it will start and finish well.

Example

function print() {
     document.getElementById("demo").innerHTML="TutorialFish!";
}
setTimeout(print, 3000);

 Try It! 

The setTimeout in this program is a process that takes a long time (3 seconds). Its first parameter is a callback function, and the second parameter is the number of milliseconds. After this function is executed, a child thread will be generated, and the child thread will Wait 3 seconds, then execute the callback function "print", and output "TutorialFish!" on the command line.

Of course, JavaScript syntax is very friendly, we don't have to define a function print separately, we often write the above program as:

Example

setTimeout(function () {
     document.getElementById("demo").innerHTML="TutorialFish!";
}, 3000);

 Try It! 

Note: Since setTimeout will wait 3 seconds in the child thread, the main thread does not stop after the setTimeout function is executed, so:

Example

setTimeout(function () {
     document.getElementById("demo1").innerHTML="TutorialFish-1!";
}, 3000);
document.getElementById("demo2").innerHTML="TutorialFish-2!";
console.log("2");

 Try It! 

The execution result of this program is:

TutorialFish-1!
TutorialFish-2!

Asynchronous AJAX

In addition to the setTimeout function, asynchronous callbacks are widely used in AJAX programming. For details about AJAX, please refer AJAX Tutorial in TutorialFish.com

XMLHttpRequest is often used to request XML or JSON data from a remote server. A standard XMLHttpRequest object often contains multiple callbacks:

Example

var xhr = new XMLHttpRequest();
 
xhr.onload = function () {
     // Output the received text data
     document.getElementById("demo").innerHTML=xhr.responseText;
}
 
xhr.onerror = function () {
     document.getElementById("demo").innerHTML="Request error";
}
 
// Send an asynchronous GET request
xhr.open("GET", "https://www.tutorialfish.com/demo_source/ajax_info.txt", true);
xhr.send();

 Try It! 

The onload and onerror attributes of XMLHttpRequest are both functions, which are called when the request is successful and when the request fails, respectively. If you use the complete jQuery library, you can also use asynchronous AJAX more elegantly:

Example

$.get("https://www.tutorialfish.com/demo_source/ajax_info.txt",function(data,status){
     alert("Data: "+ data + "\nStatus:" + status);
});

 Try It!