Last Updated: December 31, 2020
·
2.495K
· supershabam

callback correctly with immediate result

So, you're a lambda function and you're supposed to execute your callback once you have your result.

Sometimes, though, you'll have the result already. Maybe you've cached the result and don't need to make that slow call to the filesystem.

Should you execute the callback immediately?

No, here's why

The caller can be depending on you to wait your turn. It's not always the case, but you don't get to define who calls you. So don't assume.

Remember, as I write javascript code I expect each line of it to be executed before any callback functions fire.

example

function ImpatientServer() {} // extend EventEmitter
ImpatientClass.prototype.listen = function(port, cb) {
  this.emit('listening'); // let others react
  return cb();
};

var server = new ImpatientServer();
server.listen(8080, function(err) {
  console.log('hello from the callback');
});
console.log('attaching a listener');
server.on('listening', function() {
  console.log('sadly, I will not be called');
});

The output of this example is:

1> hello from the callback
2> attaching a listener

However, we would expect this output:

1> attaching a listener
2> hello from the callback
3> sadly, I will not be called

the preferred method

Always do some sort of blocking before executing your callback.

// return the callback ASAP (but not now)
process.nextTick(function() { return cb(); });

// or in the browser set 0 delay timeout
setTimeout(function() { return cb(); }, 0);

// or most likely, pass the callback to something
db.runQuery(params, cb); // you deal with it

Yes, we want blocking. That's why you're accepting a callback. Just... don't block longer than you need to.

Typically, you don't have to think about this. You'll most likely be passing your callback function to other blocking functions such as HTTP, or filesystem operations.

The only real good reason for having a result immediately available is if you're caching results from otherwise blocking operations.

If you ever do find yourself in the possession of both a callback and an immediate result, don't be tempted to return the result immediately!