preface

Asynchronous is asynchronous….

This section can get a little boring, but it’s a very important concept in JavaScript, and it’s worth learning.

purpose

  • Improve development efficiency and write maintainable code

A matter

  • Why is the page stuck when requesting?
$.ajax({
  url: "www.xx.com/api".async: false.// true
  success: function(result) {
    console.log(result); }});Copy the code
  • Why is the data updated but the DOM not?
// Update DOM (vue-nexttick)
// <div id="app">{{num}}</div>
new Vue({
  el: "#app".data: {
    num: 0,},mounted() {
    let dom = document.getElementById("app");
    while (this.num ! = =100) {
      this.num++;
    }
    console.log("Vue num=" + this.num, "DOM num=" + dom.innerHTML);
    // Vue num=100,DOM num=0
    // nextTick or setTimeout}});Copy the code

Causes of asynchrony

Cause: single-threaded (one point in time, only one thing to do), the browser’s JS engine is single-threaded.

Single-threaded means that there is only one thread in the JS engine responsible for interpreting and executing IavaScript code, which is called the main thread.

A single thread means that only one task can be completed at a time. If you have more than one task, you must queue the first one to complete and then the next one to execute.

Let’s take a look at the browser kernel thread diagram:

Render thread and JS thread are mutually exclusive.

If you have two functions, one to modify and one to delete, operating on a DOM node at the same time, if you have multiple threads, the two threads executing at the same time will definitely be deadlocked, and there will be problems.

The reason why JS is designed to be single-threaded is because of the particular environment of the browser.

Advantages and disadvantages of single threading:

The advantage of this mode is that the implementation is relatively simple, the execution environment is relatively simple; The disadvantage is that as long as one task takes a long time, subsequent tasks must wait in line, which will delay the execution of the entire program. A common browser non-response (suspended animation) is usually the result of a single piece of Javascript code running for so long (such as an infinite loop) that the entire page gets stuck in one place and no other task can be performed.

Common clogging (dead-loop) :

while (true) {}
Copy the code

JS was designed to be a scripting language that runs in the browser, so it doesn’t want to get complicated. It’s designed to be single-threaded, meaning that you can only do one thing at a time.

To solve the problem of single-thread blocking, asynchrony is created.

Take eating instant noodles for example:

  • Synchronization: buy instant noodles = “boil water (staring) =” boil noodles = “eat instant noodles
  • Asynchronous: buy bubble noodles = “boil water (water opened hot kettle ring – callback) =” watch TV = “boil surface (face good hot kettle ring – callback) =” watch TV = “cooked call me =” eat bubble noodles

Watching TV is an asynchronous operation, and the kettle is a callback function.

Asynchronous programming

Most of the code in JS is synchronous execution, only very individual functions are asynchronous execution, asynchronous execution of the code, it needs asynchronous programming.

Asynchronous code

setTimeout(() = > {
  console.log("log2");
}, 0);
console.log("log1");
// ?? log1 log2
Copy the code

The nature of asynchronous code is that instead of executing immediately, it needs to wait and execute at some point in the future.

Synchronization code Asynchronous code
<script>code Web request (Ajax)
I/O operations Timers (setTimeout, setInterval)
rendering Promise (then)
async/await

The callback function

The most common way to write asynchronous code is to use callback functions.

  • HTTP Network request (perform xx operation after the request is successfully identified)
  • DOM event binding mechanism (user triggers event to perform xx operation)
  • Timer (setTimeout, setInterval) (xx operation is performed after the set time is reached)
// Notice that the click method is a function, not a variable
// It is the callback function
$("#btn_1").click(function() {
  alert("Btn 1 Clicked");
});
/ / or
function click() {
  // It is the callback function
  alert("Btn 1 Clicked");
}
$("#btn_1").click(click);
Copy the code

The drawback of the callback function is also obvious, which is prone to create callback hell:

Three ways to do asynchronous programming

  • callback
function getOneNews() {
  $.ajax({
    url: topicsUrl,
    success: function(res) {
      let id = res.data[0].id;
      $.ajax({
        url: topicOneUrl + id,
        success: function(ress) {
          console.log(ress); render(ress.data); }}); }}); }Copy the code
  • promise
function getOneNews() {
  axios
    .get(topicsUrl)
    .then(function(response) {
      let id = response.data.data[0].id;
      return axios.get(topicOneUrl + id);
    })
    .then((res) = > {
      render(res.data.data);
    })
    .catch(function(error) {
      console.log(error);
    });
}
Copy the code
  • async/await
async function getOneNews() {
  let listData = await axios.get(topicsUrl);
  let id = listData.data.data[0].id;
  let data = await axios.get(topicOneUrl + id);
  render(data.data.data);
}
Copy the code

The online preview

Preview address: jsrun.net/s43Kp/embed…

Problem??

If multiple asynchronous codes exist at the same time, what is the order of execution? Which came first and which came second?

Macro and micro tasks

The division of asynchronous code, asynchronous code into macro tasks and micro tasks.

Macro tasks (no rush) Microtasks (in a hurry)
<script>The overall code Promise
setTimeout/setInterval

Event loop

Order of execution:

  1. Execute overall code<script>(Macro task)
  2. Perform all microtasks
  3. Perform a macro task
  4. Executing the render thread
  5. 2 – > 3 – > 2 – > 3… Cycle through (new macro and micro tasks are created in steps 2 and 3)

Repeatedly pull tasks from the macro and microtask queues to execute them.

conclusion

For browser design reasons, JS threads and render threads are mutually exclusive, so JS threads are designed to be single threads.

Asynchrony occurs because a single thread has problems blocking certain operations, such as network requests.

Because of asynchrony, there is asynchronous programming, and hence callback functions.

Since too many callback functions can create callback hell, there’s a Promise to fix callback hell

Since the ES7 standard there is a more elegant way to write ———— async/await, which is the ultimate solution for asynchronous programming.

Because JS code is divided into synchronous and asynchronous code, synchronous code execution order needless to say, top-down execution.

But t if there are multiple asynchronous code, what is the order of execution?

In order to solve the execution order of multiple asynchronous codes, EventLoop is introduced to divide asynchronous tasks into macro tasks and micro tasks, which are executed in sequence according to rules.

Now finish!

practice

console.log("script start");
setTimeout(function() {
  console.log("timeout1");
}, 10);
new Promise((resolve) = > {
  console.log("promise1");
  resolve();
  setTimeout(() = > console.log("timeout2"), 10);
}).then(function() {
  console.log("then1");
});
console.log("script end");
Copy the code

Write the log output and give reasons for it.

reference

  • Discussion on browser multi-process and JS thread
  • Understand -JS event loop macro and micro tasks in one go
  • 【JS】 In-depth understanding of the event cycle, this article is enough! (will be)
  • Tasks, microtasks, queues and schedules
  • What are the threads of the browser

Original article from ninety