first, what is asynchronous?
We generally like to asynchronous and synchronous, parallel out of the comparison, my previous understanding is always very vague, always hard to remember that "synchronization is queued execution, asynchronous is executed together", now a look at the beginning is silly, so we first put these three concepts clear, I do not like to see some blog on the internet very vague said " XXXX is synchronous, XXXX is asynchronous ", and what is the popular example, in fact, do not understand the people are still ignorant force.
First of all, we need to know that the root of all this is "JavaScript is single-threaded ", that is, only one thing at a time, then why is single-threaded it? Because JS renders in the browser, contains many interactions with the user, if it is multi-threading, then imagine a scene: one thread to add content on one of the DOM, and another thread to delete the DOM, then how does the browser react? It's all messed up.
All tasks in a single thread need to be queued, and there are two types of tasks: synchronous and asynchronous, which are the tasks that are queued on the main thread, and only the previous task is completed to perform the latter task; The asynchronous task refers to not entering 主线程 任务队列 Queue) task, only the 任务队列 notification 主线程 , an asynchronous task can be executed, the task will go into 主线程 execution. So, synchronous execution is also a kind of asynchronous execution with only the main thread. Here's a video about how asynchronous operations are executed, and it's very good to say "what's the hack is event loop", I'll draw a picture for you to understand.
Event-loop.png
Here it is added that different asynchronous operations are added to the task queue at different times, such as the onclick, SetTimeout, Ajax processing in a different way, these asynchronous operations are performed by the browser kernel WebCore, WebCore contains the above mentioned 3 kinds of WebAPI, are DOM Binding, timer, network module, respectively.
The onclick is handled by the DOM Binding module of the browser kernel, and when the event is triggered, the callback function is immediately added to the task queue.
SetTimeout will be deferred by the timer module of the browser kernel, and the callback function will be added to the task queue when the time arrives.
Ajax is handled by the Web module of the browser kernel, and the callback is added to the task queue after the network request has finished returning.
Finally, let's say parallel, parallelism is about what can happen at the same time, is a multi-threaded operation mechanism, regardless of synchronous asynchronous is single-threaded.
second, why to use asynchronous operation
This is a good understanding, synchronization of the previous event after the execution of the last event, then if the AJAX request this time-consuming, the page will not be able to operate during this period, card there, and even if the request for some reason has not been completed, the page block, very unfriendly.
Iii. How to implement asynchronous
We can achieve asynchrony through,,, and 回调函数 Promise 生成器 Async/Await so on.
Today we first say the most basic callback function processing method to implement, to enumerate a few familiar usage scenarios, such as: Ajax request, IO operation, timer.
function(){ //这就是回调函数});setTimeOut(function(){ //回调函数}, 1000)
The callback itself is more useful, but as JavaScript matures, the callback is not enough for the development of asynchronous programming, as reflected in the following points:
1, the brain processing procedures are sequential, for complex callback functions will be difficult to understand, we need a more synchronous, more sequential way to express the asynchronous.
To illustrate:
The callback function implements two numbers to addfunctionAddGetX, GetY, CB) {var x, y; GetX (functionXval) {x=xval;if (y!=Undefined) {CB (X+Y);}}); GetY (function) {y=yval;if (x!=Undefined) {CB (X+Y);}});} Add (Fetchx, Fetchy,function (sum) {console.log (sum );}) //promise achieve two numbers add function add (xpromise, ypromise) {return promise.all ([Xpromise, Ypromise]). Then ( function (values) {return value[< Span class= "Hljs-number" >0] + value[1];}); //fetchx (), Fetchy () returns the corresponding value of Promiseadd (Fetchx (), Fetchy ()). Then ( function (sum) {console.log (sum); })
Just look at the structure is not promise the wording of the more sequential words.
2, the callback will generally give control to a third party, resulting in trust problems, such as:
- Call callback Prematurely
- Call callback too late (or not called)
- Too many or too few callback calls
- Failed to pass required environment and parameters
- Swallow possible errors and anomalies
And promise's characteristic solves these problems effectively, how is it solved?
Call callback prematurely
The main concern is whether the code introduces the class Zalgo effect, where a task is sometimes synchronized and sometimes completed asynchronously, which results in a fit state.
Promise is defined as not being affected by this concern, because even the immediately completed Promise (e.g. new Promise (function (Resolve) {resolve (42);}) ) is also not possible to be monitored synchronously. That is, but you raise the promise in the (..) , even if this promise has been resolved, you give then (..) The provided callback will always be called asynchronously .
call callback too late
When a promise is called, the then registered callback function on this promise is immediately called at the next asynchronous timing point, sequentially. None of these callbacks can affect or delay calls to other callbacks.
To illustrate:
function(){ p.then( function(){ console.log( "C" ); } ); console.log( "A" );} );p.then( function(){ console.log( "B" );} );// A B C
Why is "C" not in front of "B"? Because the. Then callback function for "C" is the tick in the next event loop.
callback not called
This is a very common concern. Promise solves it in several ways.
First, when promise is parsed, it will tell you to parse the result in case the code is not wrong. If the code has an error, it is categorized in the following "Swallow error or exception".
So what if promise itself is never parsed anyway? Then promise will use Promise.race to solve.
See the code example:
A tool that makes promise time-outfunctionTimeoutpromise (Delay) {ReturnNewPromise (function (resolve,reject) {setTimeout ( function ( "timeout!"); }, delay); } );} //set a timeout for ' foo () ' promise.race ([foo (), //try to call ' foo () ' Timeoutpromise (3000) //give it 3 seconds]). Then (function (//' foo (..) ' It's done in time! }, function (err) {//' foo () ' is not rejected, it is not finished in time //then you can investigate ' err ' to know what kind of situation});
The number of calls is too low or too
Normal is called once, "too little" is not called, refer to above; "Too much" is easy to understand. Promise is defined in such a way that it can only be resolved once, and if, in some cases, the resolution is repeated, promise will only accept the first resolution and ignore subsequent calls.
failed to pass required parameter/environment value
Promise will only have one parse result (complete or reject). If it is not explicitly parsed with a value, its value is undefined, as is common in JS.
swallowing errors or exceptions
The exception in the promise is captured and the promise is rejected.
As an example:
var p = new promise (function (resolve,reject) {foo.bar (); //' foo ' is not defined, so this is a mistake! Resolve (42); //will never run here:(}); P.then (function fulfilled (//never run Here:(}, function rejected (err) { //' err ' will be a ' foo.bar ' exception object from the ' TypeError () ' line;
Promise first said here, about PROMISEAPI and its source code there are generators, async/await in the following articles to collate reports.
"The place is not well written, please be bold to spit, thank you very much for bringing me progress." 】
Resources:
Nanyi Event-loop
Wang Fu in-depth understanding of JavaScript asynchronous series one
You don't know the JavaScript
You don't understand. js: Async and Performance Chapter III: Promise (Part One)
Hara Cheng Wendy
Links: https://www.jianshu.com/p/f4abe8c4fc2f
JS Asynchronous processing