1. jsSynchronous operationNot all tasks are meant to work together.
  2. jsAsynchronous operationsIt’s not like you finish one task and start another.

Synchronization: Single-threaded, which means only one thing is being done at a time. All synchronization is done in the main thread.

console.log(1); 
setTimeout(function(){ 
    console.log(2); 
},0) 
console.log(3)
/ / 1 to 31
Copy the code
  1. The first sentence issynchronousCode, in the main thread.
  2. Read the second sentence. It’sasynchronousCode, in the browser.
  3. Third sentence, refer to the first sentence.

So, asynchronous operations, first put asynchronous code in the browser, because browsers are multi-threaded, and return in a different order.

Simply put, when a task is not completed consecutively, it can be understood that the task is divided into two parts: the first part is performed, the other part is performed, and the second part is performed when the task is ready.

For example, file reading, the first part of the task is to send a request to the operating system to read the file. The program then performs other tasks and waits for the operating system to return the file before performing the second part of the task (processing the file). This discontinuous operation is called asynchrony.

The callback function

The JavaScript implementation of asynchronous programming is the callback function, which writes the second section of the task in a separate function that is called when the task is re-executed.

fs.readFile('/etc/passwd', 'utf-8', function (err, data) {
  if (err) throw err;
      console.log(data);
  });
Copy the code

test

console.log(-1); setTimeout(function(){ console.log(0); }, 0); setTimeout(function(){ console.log(1); }, 1000); setTimeout(function(){ console.log(2); }, 100); setTimeout(function(){ console.log(3); }, 0); setTimeout(function(){ console.log(4); }, 1000); setTimeout(function(){ console.log(5); }, 1000); setTimeout(function(){ console.log(6); },200) // - 1,0,3,2,6Copy the code