event/Asynchronous
Promise
I believe that in the interview, many students have been asked such a question: how to handle Callback Hell
. In the early years, there are lots of solutions like Q, , EventProxy. Finally from the prevalence point of view, promise has been the winner of them, and has been the part of the ECMAScript 6 specification.
To learn more basic knowledge about promise
, we recommend this article.
To distinguish the difference, you can read this article We have a problem with promises
About Synchronous or Asynchronous, I hope you can pay attention to this question, a simple promise
example below.
there is no doubt that you can get the output
hello
over
the first question is that the code wrapped by Promise is certainly synchronized, but whether the execution of then
is Asynchronous?
the second quesiton is setTimeout
and then
will be called after 10s, but how about hello
? will hello
be printed after 10s or at the beginning?
let doSth = new Promise((resolve, reject) => {
console.log('hello');
resolve();
});
setTimeout(() => {
doSth.then(() => {
console.log('over');
})
}, 10000);
and how to understand the execution order of the code below: ()
If you don’t kown the answers of these questions, you can print the output at local environment. I hope you can understand the change of promise
status, includes the relationship between promise
and asynchronous, how promise help you to handle async situation , it would be better if you know the implementations of promise
Events
module is a very important core module in Node.js. There are many important core APIs in the node that depend on Events
, for example, is implemented based on Events
, and fs
, net
, ‘http’ are implemented based on ‘Stream’, ‘Events’ is so important to Node.js.
A class or a Object can get basic events
methods by extending EventEmitter
class, and we call it ‘emitter’, and the callback funciton that emit a kind of event is called as ‘listener’. It is diffrent from DOM tree in browser, there are no bubble and capture actions or methods to handle event.
Blocking/non-blocking
How to judge whether a interface is asynchronous? Is it asynchronous while a callback provided?
This is a open question, you can have your own way to judge.
- review documentation
- whether there is IO operation
Simply use the callback function is not asynchronous, IO operation may be asynchronous, in addition to the use of setTimeout and other ways are asynchronous.
In Node.js environment javascript code has only one single thread. Only the current code has been excuted, the process will cut into the event loop, and then pop out the next callback function from the event queue to start the implementation of the code. so ① to implement a Sleep function, as long as an infinite loop can block the execution of the entire js process (on how to avoid the colleagues write deadless loop, see the chapter of test
.)
How to implement a Sleep function? ①
var start = Date.now(), expire = start + ms;
while (Date.now() < expire) ;
return;
}
If endless loop logic trigger in your website, the whole process will be blocked, and all request will timeout, asynchronous code will never be excuted, and your website will be crashed.
You need to konw that reduce is analyze a recursive data structure and through use of a given combining operation, recombine the results of recursively processing its constituent parts, building up a return value.
The writter think there are two kinds of ‘asynchronous’ in Node.js: hard asynchronous
and soft asynchronous
.
hard asynchronous
means IO operation or some cases that you need libuv module externally and of course includes readFileSync
or execSync
. Because of the single thread feature of Node.js, it is unwise to do some IO operation in synchronous way as it will block the excutation of other code.
soft asynchronous
is that some asynchronous cases implemented by setTimeout
. To understand the diffrence among nextTick, setTimeout and setImmediate , you can see this article.
Event loop example
┌───────────────────────┐
┌─>│ timers │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ I/O callbacks │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
│ │ idle, prepare │
│ └──────────┬────────────┘ ┌───────────────┐
│ ┌──────────┴────────────┐ │ incoming: │
│ │ poll │<─────┤ connections, │
│ └──────────┬────────────┘ │ data, etc. │
│ ┌──────────┴────────────┐ └───────────────┘
│ │ check │
│ └──────────┬────────────┘
│ ┌──────────┴────────────┐
└──┤ close callbacks │
To know more about event loop, Timers, nextTick, we recommend the Node.js documentation, The Node.js Event Loop, Timers, and process.nextTick() and .
Paraller/Concurrent
Parallelism and Concurrency are two very common concepts. You can read this blog of Joe Armstrong(the creator of Erlang) ()
Coucurrent = 2 queues with 1 coffee machine
Parallel = 2 queues with 2 coffee machines
Node.js executes each task of events queue one by one by event loop, by this way, it avoids that in some traditional multithreading situation, when ‘2 queues with 1 coffee machine’, the context switch and resource scramble/synchronize problems, and achives high concurrent。