Nodejs was hit with a single-threaded, non-blocking, event-driven ... etc. label. In the case of a single thread, the child thread cannot be opened. After a long study, found that there is no thread function!!! But sometimes we do need "multithreading" to handle transactions. Nodejs has two very basic api:settimeout and setinterval. Both of these functions can be "asynchronous". Asynchronous implementation of Nodejs: Nodejs has a task queue that, when using the SetInterval function, adds tasks to the task queue at specific times, enabling "multitasking" processing. However, "specific time" does not mean a specific time, it may be greater than the time we set, or may be less than. Let's run the code block below.
setInterval(function() { console.log(new Date().getTime());}, 1000);
The results of the output are as follows:
14905313906401490531391654149053139266014905313936651490531394670149053139567014905313966721490531397675......
We can see that all the time intervals are not the same. The offset of time includes not only the 1s of the interval, but also the time-consuming of console.log () and the time-consuming of the new Date (). In a large number of statistics, the time interval is approximately 1s.
Here's the problem. , SetInterval is a multi-tasking effect, but how can we achieve synchronous operation between tasks? The method implemented here is implemented through the callback function .
function a (callback) {//simulation task a time consuming setTimeout (function () {Console.log (//callback task B callback ();}, 3000);}; function b () {setTimeout (function () {Console.log ( "task B end!"), 5000);} A (b);
Here is a very simple example, that is, the implementation of the B method is assigned to the callback function of the A method to implement a function callback, but there is a problem. Suppose the A method relies on the B method, the B method relies on the C method, and the C method relies on the D method ... it also means that the implementation of each method needs to hold an instance of the previous method to implement the callback.
function a (b, C, D) {Console.log ( "Hello a"); B (c, d);}; function b (c, D) {Console.log ( "Hello B"); C (d);}; function c (d) {console.log ( "Hello C"); D ()}; function d () {Console.log ( "Hello D");}; A (b, C, D);
Output results
ahello bhello chello d
If the callback function is written more, it will make the code particularly disgusting.
It would be nice if you had a function like sync that would allow the task to execute sequentially. Finally found the async this library $ npm instanll Async
Async =Require"Async"); a =function(callback) {Delay 5s analog time-consuming Operation SetTimeout (function() {Console.log ("Hello World A");Callback to the next function callback (Null"Function A"); },5000);}; b =function(callback) {//delay 1s analog time-consuming Operation SetTimeout ( function () {Console.log ( "Hello World B"); //callback to the next function callback (null, " function B ");}, Span class= "Hljs-number" >1000);}; c = function (callback) { Console.log ( "Hello World C"); //callback to the next function callback (null, " function C ");}; //execute async.series in order of B, A, C ([B, A, c], function
The comment basically can be understood very well, we look at the output
'function b', 'function a', 'function c' ]
The implementation of the basic async module above if you know more about the use of async modules, You can click: View Details
In fact, the Nodejs Basic API also provides an asynchronous way to implement synchronization. the implementation based on Promise+then
function (time) { return new Promise(function () { setTimeout(function () { console.log("end!"); }, time); });};console.log(sleep(3000));
The output is:
Promise { <pending> }end!
As can be seen, here returned the Promise object, the direct output promise object, will output the state of the object, there are only three kinds: PENDING, fulfilled, rejected. The literal meaning is well understood. That is to say, promise has the potential to implement our asynchronous task synchronous execution function. We first use Promise+then to implement asynchronous task synchronization operations.
Sleep =function() {return new Promise (function (resolve, reject) {setTimeout ( function () {Console.log ( "start!"); Resolve (); }, 1000); }) . then (function () {setTimeout (function 2000);}) . then (function () {Console.log (1000))
Output Result:
Promise { <pending> }start!end!!end!
After the new Promise task finishes executing, the call to resolve executes all the then functions, and the then functions are executed asynchronously. Can be known by the output results. (If all then is executed sequentially, it should be end!.) end!! )。 But the above also did two asynchronous tasks between the sequential execution.
However, there is a more elegant way: using async+await.
display =function (time, string) {return Span class= "Hljs-keyword" >new Promise (function (Resovle, reject) {setTimeout (function //execution order: b A cfn = Async function Span class= "Hljs-params" > () {//will cause blocking await display (5000, "B"); Await display (3000, "a"); await display ( 5000, "C");} ();
Output Result:
bac
Because of the time output here is awkward, can only be sensed through us, I know through the personal "perception" in display B over to display a when the approximate use of 3s, and then over to display C when the approximate use of 5s