Will03uk Will03uk - 1 year ago 66
Javascript Question

The javascript/nodejs concept

I'm finding it really hard to get the JS callback concept. I understand it is a web of functions waiting to be called by its parent but what's the advantage of this? How is nodejs non blocking? Would the following definitely give "hello world" or could it be either as its the first one too be called? Does nodejs switch context, because how would it step over functions waiting to be called back? I understand this question isn't well organized as I am really confused, for more info just comment.

SomeProccess(function() {

OtherProccess(function() {

Answer Source

This completely depends on whether the code is blocking or non-blocking.

If the code is blocking then SomeProcess will do something then call the function that prints "hello". If it's non blocking that means it either passes control to a sub process or does message passing down a stream and then does some other stuff later when a message comes back.

// Blocking
function SomeProcess(cb) {
    for (var i = 0; i < 10; i++) {

// Non blocking
function SomeProcess(cb) {

If functions are blocking then you can garantuee order. If there non blocking then there's no garantuee.

Non blocking:

  • process.nextTick
  • setTimeout / setInterval
  • child_process.spawn
  • streams

In node.js you can assume that all IO is non blocking. node.js internally has a queue of blocking work to do. (call functions) and once that work is done it goes back to the event loop and grabs a new set of blocking work to do, which is either handle incoming messages from streams or handle timeouts or handle process.nextTick events.

one thing to note is that EventEmitter.emit is blocking, it will resolve all bound event handlers immediatly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download