SoFunction
Updated on 2025-03-10

A brief discussion on asynchronous execution of js

The execution environment of the language is "single thread":

Advantages: It is relatively simple to implement and the execution environment is relatively simple;

Disadvantages: As long as there is a task that takes a long time, the subsequent tasks must be queued up, which will delay the execution of the entire program. Common browsers are unresponsive (fake death) often because a certain piece 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 executed.

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

2. Several methods for programming "asynchronous mode":

(1) Callback function:The advantages are simple, easy to understand and deploy, the disadvantage is that it is not conducive to the reading and maintenance of code, and the high coupling between various parts (coupling) makes the program structure confusing and the process difficult to track (especially when callback functions are nested), and each task can only specify one callback function.

(2) Use event-driven mode (event listening):The advantage is that it is relatively easy to understand. Multiple events can be bound, and multiple callback functions can be specified for each event, and it can be "decoupling" (Decoupling), which is conducive to modularization. The disadvantage is that the entire program will become event-driven, and the operation process will become very unclear.

(3) Observer mode (Publish\Subscribe mode):The nature of this method is similar to "event listening", but is significantly better than the latter. Because we can monitor the operation of the program by looking at the "Message Center" to understand how many signals exist and how many subscribers are for each signal.

3. Process control of asynchronous operations.

(1) Serial execution:Write a process control function to control asynchronous tasks. After one task is completed, execute another.

var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
function series(item) {
 if(item) {
  async( item, function(result) {
   (result);
   return series(());
  });
 } else {
  return final(results);
 }
}
series(());

Function series is a serial function. It will execute asynchronous tasks in turn. Only after all tasks are completed will the final function be executed. The items array holds the parameters of each asynchronous task, and the results array holds the running results of each asynchronous task.

(2) Parallel execution:All asynchronous tasks are executed at the same time, and the final function is executed only after all is completed.

//The forEach method will initiate 6 asynchronous tasks at the same time, and the final function will not be executed until they are all completed.var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];

(function(item) {
 async(item, function(result){
  (result);
  if( == ) {
   final(results);
  }
 })
});

The advantage of parallel execution is that it is more efficient, and it saves time compared to serial execution. But the problem is that if there are many parallel tasks, it is easy to exhaust system resources and slow down the running speed. Therefore, there is a third process control method.

(3) The combination of parallel and serial:Set a threshold, at most n asynchronous tasks can be executed in parallel at a time. This avoids excessive use of system resources.

//Variable running records the number of tasks currently running. As long as it is lower than the threshold value, a new task will be started.//If it is equal to 0, it means that all tasks have been executed, and then the final function is executed//At most, only two asynchronous tasks can be run simultaneously.var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;

function launcher() {
  while(running < limit &&  > 0) {
    var item = ();
    async(item, function(result) {
      (result);
      running++;
      if( > 0) {
        launcher();
      }
    });
    running--;
    if(running == 0) {
      final();
    }
  }
}

The above is the full content of the asynchronous execution of js brought to you by the editor. I hope everyone can support me~