as understand, differences between process.nexttick() , setimmediate() followings:
- callbacks scheduled
process.nexttick()executed before entering next event loop, while callbacks scheduledsetimmediate()executed 1 per event loop. - base on characteristics stated above, can said that: recursive call of
process.nexttick()can cause program hang up, while recursive call ofsetimmediate()not.
then i've written testing code verify statements above, here code:
process.nexttick(function() { console.log('nexttick1'); }); process.nexttick(function() { console.log('nexttick2'); }); setimmediate(function() { console.log('setimmediate1'); process.nexttick(function() { console.log('nexttick3'); }); }); setimmediate(function() { console.log('setimmediate2'); }); my expected result should
nexttick1, nexttick2, setimmediate1, nexttick3, setimmediate2
, got
nexttick1, nexttick2, setimmediate1, setimmedate2, nexttick3
then i've run test study behavior of setimmediate():
//the following code using express framework app.get('/test', function (req, res) { res.end('the server responding.'); }); app.get('/nexttick', function (req, res) { function callback() { process.nexttick(callback); } callback(); res.end('nexttick'); }); app.get('/setimmediate', function (req, res) { function callback() { setimmediate(callback); } callback(); res.end('setimmediate'); }); step1: accessed http://localhost:3000/nexttick on browser , got text nexttick.
step2: accessed http://localhost:3000/test test if server still responding requests, , didn't response, browser kept waiting response. nothing surprising because recursive call of process.nexttick() had hanged server.
step3: restarted server.
step4: accessed http://localhost:3000/setimmediate , got text setimmediate
step5: accessed http://localhost:3000/test again test if server still responding. , result same step2, didn't response , browser kept waiting response.
this means behavior of process.nexttick() , setimmediate() pretty same know not.
i wondering why happening or have misunderstood sth. thank you.
p.s. running node v0.12.7 under windows 10.
actually test results looks ok (i refer first test). comments "setimmediate() executed 1 per event loop." wrong, see https://nodejs.org/api/timers.html#timers_setimmediate_callback_arg , thats reason don't understand first test results.
basically process.nexttick put function @ end of current event loop while setimmediate put @ next event loop.
but executing multiple setimmediate ok , go same next event loop.
in
setimmediate(function() { console.log('setimmediate1'); process.nexttick(function() { console.log('nexttick3'); }); }); setimmediate(function() { console.log('setimmediate2'); }); basically have put 2 function sthat invoked in next event loop, , in 1 of them put nexttick invoked @ end of same cycle @ end of same cycle. first invoke 2 setimmediate , nexttick called in first.
Comments
Post a Comment