3

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

2 Answers 2

3

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.

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

1 Comment

Just been there many times before myself :) Happy Node hacking.
1

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

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.