Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js code execution order

Node.js code execution order

Problem

First day at programming in Node today. I've been getting along nicely all day but have some across something weird. I'm probably not understanding Node's asynchronism or something.

I have a function that executes a shell command:

function puts( error, stdout, stderr ) { sys.puts( stdout ); }

Then I execute some commands:

exec( "foo", puts );
myarr.keys( "mykey", function ( err, replies ) {
   replies.forEach( function ( reply, i ) {
      exec( "bar" );
   });
});
exec( "fuzz", puts );
exec( "buzz", puts );

so the two last things that are meant to be executed are fuzz and then buzz. However, it seems that fuzz and buzz happen at some random point in the loop and bar is the thing that gets printed last (sometimes). myarr is an array that I build by connecting to a Redis database.

Do I have to force Node to do the loop synchronously or something? I am using Redis clients in the code.. could these cause problems? Any ideas? Many thanks :).

Problem courtesy of: ale

Solution

myarr.keys() takes a callback, which won't be executed until the redis query completes.

If you need 'fuzz' and 'buzz' to execute after then, and after the loop, move them into the callback function like so:

exec( "foo", puts );
myarr.keys( "mykey", function ( err, replies ) {
   replies.forEach( function ( reply, i ) {
      exec( "bar" );
   });
   exec( "fuzz", puts );
   exec( "buzz", puts );
});

It's important to note that myarr.keys() returns instantly (well, after it has sent the query to redis). This allows you to continue with other stuff, and not block the process. The callback function is how you specify code to handle the reply from redis, which could come at any point in the future.

Solution courtesy of: MattJ

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js code execution order

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×