Created
May 9, 2011 13:49
-
-
Save darscan/962548 to your computer and use it in GitHub Desktop.
And so I abandoned the Ruby to Node port after writing this:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Function.prototype.or = function(callback) { | |
var next = this; | |
return function(err, doc) { | |
if (err) { | |
callback(err, doc); | |
} else { | |
next(doc, callback); | |
} | |
}; | |
}; |
Nice one, thanks!
You should take a look at Spidernode in combination with task.js: Seamless async functions chaining using generators. See slides 37 to 39 of this presentation for details.
Thanks Till! I'd come across task.js, but not Spidernode. Will bookmark for future reference.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure, so Node.js is all about "non-blocking" calls for I/O. This means lots of callbacks. The community has settled on the following approach to callbacks:
Async function signatures look something like this:
You call it and pass a callback. When it finishes it calls the callback. Unfortunately, when you need to do a bunch of asynchronous things in sequence things become really, really messy:
Of course, we can blame the nested anonymous functions and refactor thusly:
But what if we don't want to handle errors at every step? Could we chain it up and have any error terminate the flow and be handled elsewhere? Also, notice that our functions are callbacks, not methods (they describe what they handle rather than what they do).
The code in my gist creates callback functions to wrap async methods:
Now the functions are all aync functions rather than callback functions, and the error and final result are handled in one place.
There are tons and tons of flow-control libraries out there (in fact, writing your own is a right of passage in the Node world). This was a light weight solution that worked pretty well for my needs.