The only problem with node.js code: You get one nested function expression for each outside request you make.
io.doFirst(param1, function(result1) { io.doSecond(param2, function(result2) { // work with result1 and result2 }); });It is obvious that this can quickly turn ugly. Now David Herman from Mozilla has created task.js [1], a JavaScript library that turns the above code into the much more readable code below [2].
var result1 = yield io.doFirst(param1); var result2 = yield io.doSecond(param2); // work with result1 and result2This is reminiscent of multi-threading and blocking, but it works cooperatively (no preemptive multi-tasking). The similarities don’t end there: You can also do fork-join as follows:
var [result1, result2] = yield join(io.doFirst(param1), io.doSecond(param2));That way, you can start both operations. They can finish in any order, but your code only continues after both are finished. task.js is based on generators [3], a JavaScript feature that is already in Firefox and will probably be in the next version of the ECMAScript standard [4].
Related reading: