i new in node , try use async , event behavior advantages in node. used understand node, handle event object, gonna async execution.
had try this, consider following code:
var events = require("events"); var event = new events.eventemitter(); event.on("work", function () { (var = 0; <= 10; i++) { console.log("i work " + i); } event.emit("done"); }); var async = function (cb) { event.on("done", cb); event.emit("work"); (var = 0; <= 10; i++) { console.log("async " + i); } } async(function () { console.log("i done callback!"); }); this async execution? in opinion no! why, because had read sentence many:
an event fired, go , , when have finished it, come , tell me, in meanwhile else.
like fast food restaurant scenario. code above, when event work gonna fired, following sequence happen:
- go callback
- let through loop
- output work n
- fired done event
- output done callback!
- output async n
why done callback! gonna output before async n? why here not fast food restaurant scenario, like
the work event fired, go , stuff , come when done, in meanwhile output async n
this used understand event driven behavior , async in node. confused. know, javascript works on single thread. how can write async function event emitter? think not possible, because when emit event, execute handler.
i used understand node, handle event object, gonna async execution.
this incorrect. events synchronous. when add listener, you're saving callback in object:
this._events[type].push(listener); when emit event, you're iterating array , calling each listener:
for (i = 0; < len; i++) listeners[i].apply(this, args); source code: https://github.com/joyent/node/blob/master/lib/events.js
this async execution? in opinion no!
you correct. it's async if call i/o function or use setimmediate, nexttick or timer—otherwise, it's synchronous. synchronous code being written asynchrously doesn't convert asynchrous code.
why done callback! gonna output before async n?
because when receive "done" callback call "cb":
event.on("done", cb); when cb returns, "async n" loop executed.
how can write async function event emitter?
using setimmediate or process.nexttick.
if want postpone "i work" loop execution, can wrap line events.emit ("work") nexttick.
var events = require("events"); var event = new events.eventemitter(); event.on("work", function () { (var = 0; <= 10; i++) { console.log("i work " + i); } event.emit("done"); }); var async = function (cb) { event.on("done", cb); process.nexttick (function () { //<----- event.emit("work"); }); //<----- (var = 0; <= 10; i++) { console.log("async " + i); } } async(function () { console.log("i done callback!"); }); this print:
async 0 async 1 async 2 async 3 async 4 async 5 async 6 async 7 async 8 async 9 async 10 work 0 work 1 work 2 work 3 work 4 work 5 work 6 work 7 work 8 work 9 work 10 done callback!
Comments
Post a Comment