This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021

preface

Knowledge comb -JS asynchronous programming portal

  1. Asynchrony (process threads, Chrome architecture, EventLoop)
  2. Asynchronous programming (callbacks, publish-subscribe patterns, Promise A+ specifications, Generator functions, async functions)

Understand ASYNCHRONOUS JS programming

Case analysis

Synchronization code

Const test = () => {let t = +new Date(); const test = () => {let t = +new Date(); while (true) { if (+new Date() - t >= 2000) { break; }}}; console.log(1); test(); console.log(2); console.log(3);Copy the code

Asynchronous code

Console. log(1); setTimeout(() => { console.log(2); }, 2000); console.log(3);Copy the code

Synchronous features: call results, then do other tasks

Asynchronous features: after the call, regardless of the result, continue to do other tasks

Such an explanation is elementary and the most intuitive. When threading is introduced, it makes sense, but at the same time, it’s not as intuitive and beginner friendly.

conclusion

Synchronization: After the JavaScript main thread calls a function, the main thread continues to execute the function call, and when the function call ends, the main thread performs the following tasks.

Asynchronous: After the JavaScript main thread calls a function, other threads (non-javascript main threads) perform the function call, and the main thread continues to perform subsequent tasks. (After other threads execute, the browser asynchrony mechanism places the callback function in the task queue, waiting for the main thread to execute. This process is complicated and has a lot of details to explore, but here is a general explanation, which will be analyzed in this article’s EventLoop.)

Ps: I don’t want to expand the thread too much here, just think of it as a separate processing unit. It is important to keep in mind that JavaScirpt is a single-threaded language. The core of single-threaded JavaScript asynchrony is the asynchrony that borrows multiple threads from the browser kernel. In general, the nature of asynchronism is communication between threads. EventLoop is the communication mechanism between JavaScirpt threads and other threads in the browser.

The content here does not do in-depth discussion, simple pile up their scattered understanding, no technology, all feelings.

The main purpose is to understand the difference between synchronous and asynchronous, because synchronous means that the JavaScript main thread plays by itself, while asynchronous means that the JavaScript main thread plays with other threads in the browser’s current process. The browser has a set of gameplay EventLoop mechanisms.)

At this point, all the core concepts of asynchrony come into play: synchronous, asynchronous, browser, process, thread, EventLoop. These concepts are like a pile of pearls, and then you polish the pearls, and then you find a thread to thread the pearls.

Chrome multi-process architecture

Factory – CPU

Shop floor – process (the smallest unit that a CPU can handle a single task and can have resources and run independently)

Worker – Thread (thread is the smallest unit of program execution)

Multiprocess versus multithreading

  • Multi-process: Multi-process means that two or more processes are allowed to run at the same time on the same computer system. The benefits of multiple processes are obvious. For example, you can listen to the song while opening the editor and typing code, and there is no interference between the editor and the process of the listening software.
  • Multithreading refers to multiple execution streams in a program, that is, multiple threads can be run simultaneously in a program to perform different tasks, that is, a single program is allowed to create multiple threads of parallel execution to complete their respective tasks.

Here is a brief introduction to the browser multi-process architecture. The point is not to understand the browser in depth, but to bring together the abstract concepts of application, process, and thread. Transform our traditional black box model of JS running in a browser into a complex model of programs, processes, and threads. The significance of complexity is to lay the foundation for the later understanding of more complex coroutines, task queues, NodejsEventLoop mechanism. If there is no paving the way for this step, the following road is likely to be in vain. (The goal here is to understand asynchrony, so don’t get distracted by browsers.)

Understand the multi-process architecture of the browser and understand the concepts of processes and threads. When you don’t have a clear goal, don’t go to research, because, really learn not over.

Asynchronous scenario – Timer

Timer application examples: anti – shake, throttling, countdown, animation

Simple timer code

Console. log(1); setTimeout(() => { console.log(2); }, 2000); console.log(3);Copy the code

General Execution process

  1. The main thread calls WebAPI, setTimeout
  2. Timer thread counts two seconds (JS thread is not responsible for timing)
  3. The event triggers the thread to put timer events on the task queue
  4. The main thread traverses the task queue via EventLoop

EventLoop mechanism

EventLoop mechanism on the browser side

Image reference link

Task (macro task), Microtask (microtask), Queue (task), Call stack (execution stack)

OK, the beads all seem to be clustered together, and we’re going to string them together with the historical thread.

Sorting out ideas: refer to the working principle and practice of geek time browser Li Bing

First edition: Single-threaded model

Version 2: Introduce event loops (events and loops are two different concepts)

Loop: Keep the main thread running

Event: Started when there is a task, suspended when idle

The event loop mechanism makes threads come alive

Version 3: The Multithreaded model

Fourth edition: macro tasks, micro tasks

Ps: In fact, there is only the concept of microtask, macro task is task. Each task has a microtask queue.

If you read a lot of blog posts, it’s easy to overlook a problem. What are microtasks and why? It is easy to enter a misunderstanding, Promise interview questions so many, Promise is the micro task, the micro task must have, there must be, there is reasonable. Such a way of thinking is not worth advocating.

The microtask queue, or microtask, is a balancing act against the disadvantages of task.

The downside of this task is that the callback of the task enters the task queue, which has no priority. Callbacks that indicate that the task executed first may be placed in the task queue for execution later.

In a specific scenario, changes of DOM nodes are monitored. If it is executed synchronously, other tasks will be blocked. If it is executed asynchronously, the tail of the task queue will be added, but real-time performance cannot be met. Each task has a microtask queue. After executing the task, the microTask queue in the current task is immediately checked and related callbacks are executed. That is, a MicroTask Queue is only one part of a task. Don’t be confused by the words macro and micro tasks, they are not independent, but inclusive.

Reference:

58 e3b imweb. IO/topic /…

Html.spec.whatwg.org/multipage/t…

Time.geekbang.org/column/arti…

Html.spec.whatwg.org/multipage/w…

PS: The presence of tears, I do not know what to say, as if to write a lot, and as if nothing to write, I should be a dou reincarnation.