0

I have a very basic question in node.js programming . I am finding it interesting as I have started understanding it deeper.

I came across the following code :

Abc.do1(‘operation’,2, function(err,res1) 
{
   If(err) {
        Callback(err);
    }
    def.do2(‘operation2’,function(l) {
   }
  }

My question is :

since def.do2 is written in the callback of abc.do1 ,

is it true that def.do2 will be executed after the ‘operation’ of abc.do1 is completed and the callback function gets called . If yes, is this a good programming practice , because we speak only asynchronous and non blocking code in node.js

2 Answers 2

1

Yes, you're correct. def.do2() is executed after abc.do1() is done. However, this done on purpose to make sure that do1() is done before do2() can start. If it's meant to be done in parallel, then do2() would have been outside of do1()'s callback. This code is not exactly blocking. after do1() is started, the code is still continuing on to execute everything below do1() functon (outside of do1's callback), just not do2() until do1() is done which is meant to be.

Sign up to request clarification or add additional context in comments.

Comments

1

Yes you are absolutely correct and you have given a correct example of callback function.

The main browser process is a single threaded event loop. If you execute a long-running operation within a single-threaded event loop, the process "blocks". This is bad because the process stops processing other events while waiting for your operation to complete. 'alert' is one of the few blocking browser methods: if you call alert('test'), you can no longer click links, perform ajax queries, or interact with the browser UI.

In order to prevent blocking on long-running operations, the XMLHttpRequest provides an asynchronous interface. You pass it a callback to run after the operation is complete, and while it is processing it cedes control back to the main event loop instead of blocking.

There's no reason to use a callback unless you want to bind something to an event handler, or your operation is potentially blocking and therefore requires an asynchronous programming interface.

See this video

http://www.yuiblog.com/blog/2010/08/30/yui-theater-douglas-crockford-crockford-on-javascript-scene-6-loopage-52-min/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.