ale
ale

Reputation: 11820

Node.js code execution order

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 :).

Upvotes: 3

Views: 3771

Answers (2)

MattJ
MattJ

Reputation: 7924

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.

Upvotes: 3

ControlAltDel
ControlAltDel

Reputation: 35011

using exec causes these operations to run asynchronously. You might want to look into the fs package for synchronous equivalents. Alternatively, you might want to look into a way to stack your commands before executing them all in one batch

Upvotes: 1

Related Questions