node.js - How does node event loop decide when to switch flows? -
i use nodejs on rasbperry pi control hardware pins. assuming code such as:
for (..) { executeasynccode(..) } function executeasynccode() { doasync1().then(doasync2()).then(doasync3())... }
will executed in such manner each execution of executeasynccode
separated others, meaning 2 asynchronous executions wont running @ same time. real-time verification , usage shows differently. encounter executions doasync1(..)
called 1 after other 2 executions of executeasynccode
function, , doing lot of mess during that.
to usage problem, hardware cant used in parallel, , there many cases might want execute code , rely on fact no locks required. how can such code limited not execute together? there way of knowing how event loop execute code?
all code finish executing before event loop start next context. means loop execute completion before async callbacks executed. example:
for ( var = 0; < 100000; i++ ) { console.log( 'hi!' ); settimeout( function ( ) { console.log( 'foo' ); }, 0 ); } // synchronous operation takes long time console.log( 'bar' );
will deterministically output 'hi!' 100000 times followed 'bar'
, since there nothing more in script event loop gets chance other messages run , 'foo'
output 100000 times.
if want wait first promise chain finish before starting next one, should return promise executeasynccode
can start next 1 when completes:
var previouspromise = promise.resolve(); (..) { previouspromise = previouspromise.then( executeasynccode ); } function executeasynccode() { return doasync1().then(doasync2).then(doasync3)... }
Comments
Post a Comment