Table of Contents
Purpose
Introduction question
The reasons for asynchronous generation
Asynchronous Programming
Asynchronous code
Callback function
Three ways of asynchronous programming
Online preview
Question? ?
Macro tasks and micro tasks
事件循环(Event loop)
总结
练习
Home Web Front-end JS Tutorial Take you step by step to understand asynchronous programming in JavaScript

Take you step by step to understand asynchronous programming in JavaScript

Jun 03, 2021 am 11:02 AM
javascript Asynchronous programming

This article will introduce you to asynchronous programming in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Take you step by step to understand asynchronous programming in JavaScript

Asynchronous means non-synchronous....

This section may be a bit boring, but it is a very important concept in JavaScript and is very useful. It is necessary to learn.

Purpose

  • Improve development efficiency and write easy-to-maintain code

Introduction question

  • Why does the page get stuck when requesting? ?
$.ajax({
  url: "www.xx.com/api",
  async: false, // true
  success: function(result) {
    console.log(result);
  },
});
Copy after login
  • Why is the data updated but the DOM not updated? ?
// 异步批量更新DOM(vue-nextTick)
// <p id="app">{{num}}</p>
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 after login

The reasons for asynchronous generation

Cause: single thread (one point in time, only do one thing), the browser's JS engine is single threaded caused.

Single thread means that there is only one thread responsible for interpreting and executing IavaScript code in the JS engine. You might as well call it the main thread.

The so-called single thread means that only one task can be completed at a time. If there are multiple tasks, they must be queued. The previous task is completed before the next task is executed.

First take a look at the thread diagram of the browser kernel:

Take you step by step to understand asynchronous programming in JavaScript

Among them, The rendering thread and the JS thread are mutually exclusive .

Suppose there are two functions, one modifying and one deleting, operating a DOM node at the same time. If there are multiple threads, if the two threads are executed at the same time, there will definitely be a deadlock and there will be problems.

Why JS should be designed as single-threaded, because of the special environment of the browser.

Advantages and disadvantages of single thread:

The advantage of this mode is that it is relatively simple to implement and the execution environment is relatively simple; The disadvantage is that as long as one task takes a long time, the subsequent Tasks must be queued and waited, which will delay the execution of the entire program. Common browser unresponsiveness (suspended death) is often caused by a certain piece of Javascript code running for a long time (such as an infinite loop), causing the entire page to get stuck in this place and other tasks cannot be performed.

Common blockage (infinite loop):

while (true) {}
Copy after login

JS was originally designed to be a script language that runs in the browser, so we didn’t want to make it so complicated, so we just designed It has become a single thread, that is, can only do one thing at a time.

In order to solve single-thread blockingthis shortcoming: asynchronous is generated.

Take the example of eating instant noodles:

  • Synchronous: Buy instant noodles => Boil water (staring) => Cook noodles => Eat instant noodles
  • Asynchronous : Buy instant noodles => Boil water (the water boils and the kettle sounds - callback) => Watch TV => Cook noodles (the noodles are ready and the kettle rings - callback) => Watch TV => Call me when it's done => Eat instant noodles

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

Asynchronous Programming

Most of the code in JS is executed synchronously. Only a few functions are executed asynchronously. Asynchronously executed code requires asynchronous programming. .

Asynchronous code

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

Characteristics of asynchronous code: It is not executed immediately, but needs to wait and be executed at a certain point in the future.

Network request (Ajax)I/O operationTimer (setTimeout, setInterval) Rendering operationPromise(then)async/await
Synchronous codeAsynchronous code
##<script>Code

Callback function

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

    HTTP network request (the request is successful and the xx operation is performed after identification)
  • DOM event binding mechanism (the xx operation is performed after the user triggers the event)
  • Timer (setTimeout, setInterval) (Execute xx operation after reaching the set time)
  • // 注意到click方法中是一个函数而不是一个变量
    // 它就是回调函数
    $("#btn_1").click(function() {
      alert("Btn 1 Clicked");
    });
    // 或者
    function click() {
      // 它就是回调函数
      alert("Btn 1 Clicked");
    }
    $("#btn_1").click(click);
    Copy after login
The shortcomings of the callback function are also obvious, and it is easy to produce callback hell:


Take you step by step to understand asynchronous programming in JavaScript

Three ways of 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 after login
    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 after login
    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 after login

Online preview

Preview address: http://jsrun.net/s43Kp/embedded/all/ light

Question? ?

If multiple asynchronous codes exist at the same time, what should be the order of execution? Which one is executed first and which one is executed later?

Macro tasks and micro tasks

Division of asynchronous code, asynchronous code is divided into macro tasks and micro tasks.

##<script>setTimeout/setInterval

事件循环(Event loop)

Take you step by step to understand asynchronous programming in JavaScript

执行顺序:

  • 执行整体代码<script>(宏任务)

  • 执行所有微任务

  • 执行一个宏任务

  • 执行渲染线程

  • 2->3->2->3...依次循环(在 2、3 步中又创建了新的宏、微任务)

重复从宏任务和微任务队列里拿出任务去执行。

总结

因为浏览器设计的原因,JS 线程和渲染线程互斥,所以 JS 线程被设计成了单线程。

因为单线程执行一些操作(如网络请求)时有堵塞的问题,所有产生了异步。

因为有了异步,所以产生了异步编程,从而有了回调函数。

因为回调函数写多了会产生回调地狱,所有又有了解决回调地狱的 Promise 写法

自 ES7 标准后有了比 Promise 更加优雅的写法 ———— async/await 写法,也是异步编程的最终解决方法。

因为 JS 的代码分为同步和异步代码,同步代码的执行顺序不必多说,自上而下的执行。

但是如果有多个异步的代码,他的执行顺序又是怎么的呢??

为了解决多个异步代码的执行顺序问了,有了事件循环(EventLoop),将异步任务区分为宏任务、微任务,依据规则依次执行。

至此 完!

练习

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 after login

写出 log 的输出结果,并说出理由。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Take you step by step to understand asynchronous programming in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement asynchronous programming with C++ functions? How to implement asynchronous programming with C++ functions? Apr 27, 2024 pm 09:09 PM

Summary: Asynchronous programming in C++ allows multitasking without waiting for time-consuming operations. Use function pointers to create pointers to functions. The callback function is called when the asynchronous operation completes. Libraries such as boost::asio provide asynchronous programming support. The practical case demonstrates how to use function pointers and boost::asio to implement asynchronous network requests.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Common problems and solutions in asynchronous programming in Java framework Common problems and solutions in asynchronous programming in Java framework Jun 04, 2024 pm 05:09 PM

3 common problems and solutions in asynchronous programming in Java frameworks: Callback Hell: Use Promise or CompletableFuture to manage callbacks in a more intuitive style. Resource contention: Use synchronization primitives (such as locks) to protect shared resources, and consider using thread-safe collections (such as ConcurrentHashMap). Unhandled exceptions: Explicitly handle exceptions in tasks and use an exception handling framework (such as CompletableFuture.exceptionally()) to handle exceptions.

How does the golang framework handle concurrency and asynchronous programming? How does the golang framework handle concurrency and asynchronous programming? Jun 02, 2024 pm 07:49 PM

The Go framework uses Go's concurrency and asynchronous features to provide a mechanism for efficiently handling concurrent and asynchronous tasks: 1. Concurrency is achieved through Goroutine, allowing multiple tasks to be executed at the same time; 2. Asynchronous programming is implemented through channels, which can be executed without blocking the main thread. Task; 3. Suitable for practical scenarios, such as concurrent processing of HTTP requests, asynchronous acquisition of database data, etc.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Python asynchronous programming: A way to achieve efficient concurrency in asynchronous code Python asynchronous programming: A way to achieve efficient concurrency in asynchronous code Feb 26, 2024 am 10:00 AM

1. Why use asynchronous programming? Traditional programming uses blocking I/O, which means that the program waits for an operation to complete before continuing. This may work well for a single task, but may cause the program to slow down when processing a large number of tasks. Asynchronous programming breaks the limitations of traditional blocking I/O and uses non-blocking I/O, which means that the program can distribute tasks to different threads or event loops for execution without waiting for the task to complete. This allows the program to handle multiple tasks simultaneously, improving the program's performance and efficiency. 2. The basis of Python asynchronous programming The basis of Python asynchronous programming is coroutines and event loops. Coroutines are functions that allow a function to switch between suspending and resuming. The event loop is responsible for scheduling

What are the advantages and disadvantages of asynchronous programming in PHP? What are the advantages and disadvantages of asynchronous programming in PHP? May 06, 2024 pm 10:00 PM

The advantages of asynchronous programming in PHP include higher throughput, lower latency, better resource utilization, and scalability. Disadvantages include complexity, difficulty in debugging, and limited library support. In the actual case, ReactPHP is used to handle WebSocket connections, demonstrating the practical application of asynchronous programming.

Python asynchronous programming: Reveal the essence of asynchronous programming and optimize code performance Python asynchronous programming: Reveal the essence of asynchronous programming and optimize code performance Feb 26, 2024 am 11:20 AM

Asynchronous programming, English Asynchronous Programming, means that certain tasks in the program can be executed concurrently without waiting for other tasks to complete, thereby improving the overall operating efficiency of the program. In Python, the asyncio module is the main tool for implementing asynchronous programming. It provides coroutines, event loops, and other components required for asynchronous programming. Coroutine: Coroutine is a special function that can be suspended and then resumed execution, just like a thread, but a coroutine is more lightweight and consumes less memory than a thread. The coroutine is declared with the async keyword and execution is suspended at the await keyword. Event loop: Event loop (EventLoop) is the key to asynchronous programming

See all articles
Macro tasks (not in a hurry)Micro tasks (in a hurry)
Overall codePromise