Showing posts with label async. Show all posts
Showing posts with label async. Show all posts

Friday, June 15, 2012

How to use named functions with Async waterfall in node.js

Lets start with a real world example where you want to create a user in CouchDB. This is a two step process that involves asking for a unique uuid and then creating a user based on that.
  • The following code (+/-) abstracts out each individual step:
  • But once you have the abstracted methods, how do you chain their results? This is where the waterfall approach from the Async NPM package comes in.
  • Since you've already abstracted your methods, you may try something like this (+/-) to make them a little more waterfall friendly:
  • And then you may try the simplest way you can think of asking waterfall to run:
  • But that will fail to run because the syntax of the sentence has ended up being written in a manner where callback must be a variable that is already defined and ready to be used. Making an anonymous method here and bringing up the entire code bodies of the abstracted named-methods would defeat the readability and reuseability that we have been trying to achieve. Here's a tweak that will make it happen: