javascript - how to defer resolve tasks in nodejs -


i new nodejs, not sure how arrange tasks in order such behave correctly.

below 2 examples

arr.foreach(function(elem){     //do many many things }); console.log('done, take ur pick'); stdin.on('input', function action(){     ... }) 

how can set stdin.on fire after arr.foreach. , question 2 think if do

fn1(); fn2();  function fn1(){     //long long code }  function fn2(){     console.log('fn2 done!') } 

and runs above, execution in thread of

fn1 fn2 fn1 fn1 fn1, right? how prevent this?

functions in node.js either synchronous or asynchronous. synchronous code runs in single thread, , behaves code you're used to:

fn1(); fn2(); fn3(fn4()); 

will run fn1, fn2, fn4, fn3 (passing in result of fn4 parameter).

asynchronous code fires off action, , takes parameter function execute when it's done (which might, in turn, fire off asynchronous action). control immediately. example:

dosomeasyncthing(function () {     console.log("did async thing"); }); console.log("hello"); 

executes this: first, asynchronous action fired off, "hello" printed. time later, asynchronous action completes, callback called, , "did async thing" printed.

if want 1 asynchronous thing, asynchronous thing after first 1 finished, standard way nest callbacks:

async1(function() {     async2(function() {         console.log("async1 , async2 finished");     }); }); 

although there better options.

so in second example, if fn1 synchronous, work wrote it. if fn1 has asynchronous, have asynchronous, have write this:

function fn1(callback) {     // sync stuff     dosomethingasync(function () {         // more sync stuff         dosomethingmoreasync(function () {             // more sync stuff             callback(); // call callback once completed         });     }); } 

and call this

fn1(function () {     fn2(); }); 

which simplified to:

fn1(fn2); 

in first example, note array.foreach synchronous. if // many many things synchronous, work wrote it, if there's asynchronous action in there, can either manually implement counter, or use async library or promise iterator utilities.


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

inno setup - TLabel or TNewStaticText - change .Font.Style on Focus like Cursor changes with .Cursor -