I have been programming with Node.js for a little while, and I have found myself becoming increasingly annoyed with the need to chain callbacks. For example, when you need multiple models from a database as shown:
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
Schedule.findOne({'person_id': person.id }, 'events', function(err, schedule) {
...
}
})
I am looking for solutions to this problem. One idea I had was to do something like this:
function() {
var p;
var s;
var done = false;
Person.findOne(..., ..., function(err, person) {
p = person;
done = true;
});
while(!done){}
done = false;
Schedule.findOne(..., ..., function(err, schedule) {
s = schedule;
done = true;
});
while(!done){}
done = false;
// ...
}
If I do my queries like this, what are the performance implications? I'm also open to other ideas for solving this problem.
To answer your most direct question, the performance implication of spin-waiting for a callback is that the spin-wait may starve other, more useful tasks from being completed, either in the same process or on the same machine. If your application were running on a single-user machine with no power management, this wouldn't matter, but neither of those things is likely. Busy-waiting will destroy battery life on mobile platforms, increase electricity costs in the datacenter, and make future maintainers of the code curse your name!
As elclanrs already suggested in a comment, you could look at the "async" library to help streamline your code, but in any case you should avoid busy waiting.