beginner node.js callback example

Problem

I'm pretty novice in nodejs This is a very easy php example that I want to write in nodejs

$key='foo';
$inside= openthedoor($key);
if(!$inside){ //wrong key
   $key= getanewkey();//get a new key
   $inside= openthedoor($key);//open the door again
}

How can I do this callback in nodejs?
appologies for the stupid question.

Problem courtesy of: Ben Scarberry

Solution

Keep in mind that you can still write things synchronously in Node.js, but if openthedoor() did happen to require a callback function, this is what it'd look like:

var key = 'foo';
openthedoor(key, function(inside) {
  if (!inside) {
    key = getanewkey();
    openthedoor(key, function(inside) {
      // check if we're inside again
    });
  }
});

A callback function is a function that is called on completion of another function. In the example, you are passing this function:

var callback = function(inside) {
  if (!inside) {
    // do something else
  }
});

Into this function to be called when there is a result:

openthedoor(key, callback);
Solution courtesy of: hexacyanide

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.