This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
preface
Knowledge comb -JS asynchronous programming portal
- Asynchrony (process threads, Chrome architecture, EventLoop)
- Asynchronous programming (callbacks, publish-subscribe patterns, Promise A+ specifications, Generator functions, async functions)
Asynchronous programming – Preface
Asynchronous programming refers to the methods, techniques, and classes used in the EventLoop mechanism. Note that this is the entire EventLoop mechanism, not a single process. Having a sense of system helps you not get lost in the conceptual terms that follow. When you are lost, please come back to this picture and think about where you feel you are.
Asynchronous programming – callback functions
Emphasis: callback function, a task that continues after an operation has been performed.
(Here we are concerned with tasks that continue to be executed after an asynchronous operation. If the operation is synchronous, perform it in sequence.)
According to the asynchronous mechanism, other threads add tasks to the task queue after performing asynchronous operations. When the javaScript main thread has finished executing all the functions in the stack, javaScript checks the MicroTask queue in the current task and executes the microtasks in turn.
Obviously asynchronous callbacks in JavaScript are encapsulated as Tasks or microtasks and are handled in the Event Loop mechanism. That is, the callback function is a Loop in the Event Loop mechanism.
Summary:
- Asynchronous callback function, the first need to have asynchronous operation (without asynchronous operation, the task queue does not change, just ordinary function execution)
- Callbacks are encapsulated as macro or micro tasks that participate in the Event Loop mechanism
- Microtasks can pass
queueMicrotask()
Operation, use with care to prevent dead circulation (Refer to the MDN) - The underlying implementation of the EventLoop callback mechanism is done by the browser
- The callback function is just a noun, it’s just a normal function, well that’s it, it just comes up in asynchrony, and it’s given a convenient name.
Asynchronous programming – Event publishing subscription
Publish and subscribe model
Understanding publish subscriptions
Json ("./test1.json", function(data) {console.log(data); ajax("./test2.json", function(data) { console.log(data); ajax("./test3.json", function(data) { console.log(data); }); }); }); Const PBB = new PubSub(); ajax("./test1.json", function(data) { pbb.publish("test1Success", data); }); pbb.subscribe("test1Success", function(data) { console.log(data); ajax("./test2.json", function(data) { pbb.publish("test2Success", data); }); }); pbb.subscribe("test2Success", function(data) { console.log(data); ajax("./test3.json", function(data) { pbb.publish("test3Success", data); }); }); pbb.subscribe("test3Success", function(data) { console.log(data); });Copy the code
Advantages:
- One-to-many (not shown in this example refer to the VUE bidirectional binding implementation)
- Low coupling flexibility
Disadvantages:
- Unable to ensure that the message is triggered, several times
Publish and subscribe implementation
Class PubSub {constructor() {this.events = {}; } publish(eventName, data) { if(this.events[eventName]){ this.events[eventName].forEach(cb => { cb.apply(this, data) }); } } subscribe(eventName, callback) { if (this.events[eventName]) { this.events[eventName].push(callback); } else { this.events[eventName] = [callback]; } } unSubcribe(eventName, callback) { if (this.events[eventName]) { this.events[eventName] = this.events[eventName].filter( cb => cb ! == callback ); }}}Copy the code
Summary:
- The event scheduler in asynchronous programming adopts PubSub
- This model can be used in a lot of situations, not just asynchronous programming, it’s really nice, it’s really nice in one-to-many, you just need to focus on that one, you can wait until you use it, it’s very comfortable.
- Don’t think too much about asynchrony, it doesn’t matter. Just use, use very comfortable to use.
- Event dispatchers, EventEmitter, actually publish events after they are captured. The actual scenario in which a macro task in a task queue is executed in an EventLoop when the related callback function is executed is related to event bubbling. They’re called events, but in an EventLoop, it’s just a macro task. There’s not that much inner drama, the focus is on events bubbling, and events bubbling is not in the asynchronous flow of EventLoop. The event bubbling can be found in the Winter Repre – terminal introduction reference link
- EventEmitter in Nodejs
Asynchronous programming -Promise
Promise specification reference Promise handwritten reference
Key points of Promise
State state
pending
.fullfilled
.rejected
.- For the initial
pending
Once changed, it cannot be changed
Value of 2.
- Promise status to
fulfilled
As for thevalue
- Promise status to
rejected
As for thereason
This is a big pity, onRejected.
-
The Promise state will be fulfilled gradually, which is a big pity
-
When the Promise state changes to Rejected, onRejected is implemented
-
The then method can be called multiple times by the same Promise object
-
The then method must return a promise object, such as promise2 = promise1. Then (onFulfilled, onRejected);
PromiseA+ Spec Details (All Emotion without Technology)
Find areas of ambiguity in the specification and comb through areas that are not well understood
Part1: then method
Analysis: Most of the then method in the PromiseA+ specification is pretty well understood except for the evil expansions. But there’s no doubt that the stuff that confuses you is the key to fully understanding the PromiseA+ specification.
// PromiseA+ promises that are not easy to understand. Then (ondepressing, OnFulfilled and onRejected can not be called until the implementation environment stack contains all the platform code. Then methods can be called many times by the same Promise. When the promise is successfully executed, All ondepressing needs to be called back according to its registration order. When the promise is rejected, This method must return a promise object, such as promise2 = promise1. Then (onFulfilled, onFulfilled); If onFulfilled or onRejected returns a value x, then run the following Promise solution: [[Resolve]](promise2, x) If ondepressing or onRejected throws an exception, promise2 must be fulfilled. If onFulfilled is not a function and promise1 performs successfully, promise2 must perform successfully and return the same value. If onFulfilled is not a function and promise1 refuses to perform, Promise2 must reject execution and return the same dataCopy the code
Promise is an asynchronous task, and the callback task must be placed in the task queue or the microtask queue, depending on the language. ES6 is added to the microtask queue to prevent too many task queues.
2. All variations of the publish/subscribe model. State changes are event publications, and then method calls are event subscriptions. Promises are both the publisher and the event center. (Observer mode)
The value x is a new asynchronous task. The value x is a new asynchronous task. Promise2 is essentially a trace of this new asynchronous task.
Case Reference link
var p1 = new MyPromise((resolve, reject) => { console.log('hhh') setTimeout(() => { resolve(1) }, 1000); }).then(res => { return new MyPromise((resolve, reject) => { setTimeout(() => { resolve(res+1) }, 1000); }) }).then(res => { console.log(res); return res; }) author: star delay links: https://juejin.cn/post/6883121706123132936 source: rare earth nuggets copyright owned by the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.Copy the code
part2: The Promise Resolution Procedure[[Resolve]](promise, x)
A. Promise B. Promise C. Promise D. Promise The type of the return value x determines the processing of the promise when the chain call is made.
summary
- Promise is an asynchronous solution
- It is suitable for executing multiple asynchronous tasks in a row
- Asynchronous task execution/rejection callback can be added flexibly, and can be executed after execution/rejection
- ES6 also has new apis that provide convenient interfaces for different scenarios of a set of tasks
Asynchronous programming -Generator
Core concept: coroutine
Core function: suspend the execution of the program
Introduction: One program, multiple processes. One process, multiple threads. One thread, multiple coroutines, only one coroutine running at the same time. Thread execution is in kernel mode, is controlled by the operating system; The execution of the coroutine is in user mode and is completely controlled by the program. Coroutine switching is performed in user mode, while thread switching needs to be switched from user mode to kernel mode. Scheduling in kernel mode makes coroutines more lightweight and efficient than threads.
Description: The coroutine can be made to execute by calling the generator’s next() method, paused by the yield keyword to yield control of the main thread, and terminated by the return keyword.
Function * genDemo() {console.log(" start executing first paragraph ") yield 'generator 2' console.log(" start executing second paragraph ") yield 'generator 2' Return 'generator 2'} let gen = genDemo() return 'generator 2'} let gen = genDemo() console.log(gen.next().value) console.log(gen.next().value)Copy the code
Asynchronous programming -Async/Await
Core concept: Promise + Generator
Async function foo() {console.log(1) let a = await 100 console.log(a) console.log(2)} console.log(0) foo() console.log(3)Copy the code
Async function foo() {console.log(1) // 3. foo coroutine print 1 let a = await 100 // 4. Wrap promise execute resolve(100) then execute add the following two lines of code to the queue for the message and switch to the parent coroutine console.log(a) // 6. Assign 100 to A print 100 console.log(2) // 7. Print 2} console.log(0) // 1. The current coroutine is called the parent coroutine and prints 0 foo() // 2. Switch to foo coroutine console.log(3) // 5. The parent coroutine prints 3Copy the code
Ps: The presence of tears, I do not know what to say, is still that can not help the dou