Skip to content
Newer
Older
100644 93 lines (50 sloc) 4.59 KB
c81a2c2 @isaacs Article about flow control with callbacks in npm
isaacs authored Sep 1, 2010
1 Title: Flow Control in npm
2 Date: 2010-08-31T22:29:18
3 Author: Isaac Z. Schlueter
4 node: 0.2.0
5
6 Flow control is a popular subject in NodeJS. Since most of us learned synchronous object-oriented programming patterns in school, it can be a bit of a shift to really leverage asynchronous functional programming for all it can do.
7
8 As it turns out, a great way to leverage huge chunks of the node API is to build a package manager. npm has to do a lot of stuff with the file system, child processes, and HTTP requests to the registry. Fetching and building packages is a lot of "laundry list" programming. That is, the algorithms are very simple (fetch this file, put it over there, run that script, etc.), but there's a lot to do, and you've gotta make sure everything gets done right (and in the right order).
9
10 To keep this from getting out of hand, I've leveraged two fairly low-level patterns that are found throughout the NodeJS API, but which I haven't seen documented anywhere yet, and which I'm calling "the Action/Callback pattern".
11
12 ## Action functions
13
14 Action functions can take a variable amount of arguments, but the *last* argument is always a callback function. It MUST call that cb exactly one time, once it's done doing stuff.
15
16 ## Callback functions
17
18 Callback functions can take any number of arguments, but the *first* argument is always an error or null.
19
20 ## Example
21
22 You've probably seen this example:
23
24 <flow-control-in-npm/read-file-example.js*>
25
26 `fs.readFile` is an action function. The function being passed to it, `function (er, data)...` is a callback function.
27
28 ## Consistent Patterns are Consistent
29
30 Every function in npm, if it does something async, does it using this mechanism.
31
32 Every callback function in npm, will expect an error argument as the first argument, so calling it like that will always bubble the error up.
33
34 ## Polymorphism Wins
35
36 Because of this consistent pattern, there is a lot of room for powerful creativity.
37
38 ### `asyncMap(list, fn, cb)`
39
40 Let's say you have a list of filenames, and you have to remove each one. A pretty typical use case in npm, but once you generalize "do this to those", you start noticing nails in need of a hammer.
41
42 `asyncMap` is the answer for that. (The current async-map.js in npm is a bit more complicated, because it allows you to specify a list of functions rather than just one.)
43
44 <flow-control-in-npm/async-map.js*>
45
46 Note that the top-level `cb_` function is called with an array of all the results. So, data is being proxied up, as well as errors. (That's why it's called async**Map**, rather than async**ForEach**.)
47
48 So, now we can simply do this:
49
50 <flow-control-in-npm/remove-file-list.js*>
51
52 ### Proxying
53
54 You catch that? An Action function can pass its own cb over to another Action function if it doesn't need to do anything with success or failure. We could also have done something like this:
55
56 <flow-control-in-npm/proxying.js*>
57
58 ### `chain(fn1, fn2, ..., cb)`
59
60 There are other cases where you want to make sure that a list of functions are called in a specific order. For instance, we need to make sure that all `preinstall` scripts are done running before starting in on the `install` scripts. That's where `chain` comes in handy.
61
62 `chain` takes a list of function arguments which take a callback, and a final argument which is the ultimate callback function.
63
64 <flow-control-in-npm/chain.js*>
65
66 ### chain 2
67
68 This is great, but it requires using Function#bind if we want to pass arguments to those functions other than a callback. This API would be nice:
69
70 <flow-control-in-npm/chain2-usage.js*>
71
72 Basically, each argument is one of:
73
74 * a function which will be called with a single cb argument
75 * an array containing a function and 0 or more arguments
76 * an array containing an object, a method name, and 0 or more arguments
77 * a falsey value, so we can do stuff like:
78 foo && [ doFoo, foo, bar ]
79
80 Revamped to handle this calling style, chain looks like this:
81
82 <flow-control-in-npm/chain2.js*>
83
84 ## Mix and Match
85
86 Because everything in npm (and a lot of things in node) use this pattern, you can mix very high-level operations with very low-level operations. Why, even `chain` and `asyncMap` are "action" functions, so they can take any vanilla callback, or be arguments to one another.
87
88 This is without any sophisticated "async flow control" library. Just a few short JavaScript functions and an adherence to a few simple patterns.
89
90 As long as you stick to these patterns, you can use any Action function in any asyncMap or chain call, and make sure that all Action functions call their cb exactly once.
91
92 Get creative! This language is powerful, and it's not that hard to do interesting things with it.
Something went wrong with that request. Please try again.