As you may know, the execution environment for a JavaScript language is "single-threaded" (single thread).
The so-called "single thread" means that only one task can be completed at a time. If you have more than one task, you must queue, the previous task completes, then the next task, and so on.
The advantage of this model is that it is simpler to implement and a relatively simple execution environment; The downside is that as long as one task takes a long time, the tasks that follow must be queued up, delaying the execution of the entire program. The common browser is unresponsive (suspended animation), often because a section of JavaScript code runs for a long time (such as a dead loop), causing the entire page to be stuck in this place, and other tasks cannot be performed.
To solve this problem, the JavaScript language divides the execution pattern of a task into two types: synchronization (synchronous) and asynchronous (asynchronous).
"Sync Mode" is the pattern of the previous paragraph, the latter task waits for the previous task to finish, then executes, the sequence of execution of the program is consistent with the order of the task, synchronized; "Asynchronous mode" is completely different, each task has one or more callback functions (callback), the previous task is finished, Instead of performing the latter task, the callback function is executed, and the latter task is executed at the end of the previous task, so that the sequence of execution of the program is inconsistent and asynchronous with the order in which the task is ordered.
"Asynchronous mode" is very important. At the browser end, a lengthy operation should be performed asynchronously to avoid the browser losing its response, the best example being Ajax. On the server side, "asynchronous mode" is even the only pattern, because the execution environment is single-threaded, and if all HTTP requests are allowed to execute synchronously, server performance can plummet and quickly lose its response.
This article summarizes the 4 methods of "Asynchronous mode" programming, and understands that they allow you to write JavaScript programs that are more structured, better performing, and easier to maintain.
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/