There are no reviews yet. Be the first to send feedback to the community and the maintainers!
Repository Details
A flow control library that fits in a slideshow
Controlling Flow: callbacks are easy
What's actually hard?
Doing a bunch of things in a specific order.
Knowing when stuff is done.
Handling failures.
Breaking up functionality into parts (avoid nested inline callbacks)
Common Mistakes
Abandoning convention and consistency.
Putting all callbacks inline.
Using libraries without grokking them.
Trying to make async code look sync.
Define Conventions
Two kinds of functions: actors take action, callbacks get results.
Essentially the continuation pattern. Resulting code looks similar
to fibers, but is much simpler to implement.
Node works this way in the lowlevel APIs already, and it's very ๏ฌexible.
Callbacks
Simple responders
Must always be prepared to handle errors, that's why it's the first argument.
Often inline anonymous, but not always.
Can trap and call other callbacks with modified data, or pass errors upwards.
Actors
Last argument is a callback.
If any error occurs, and can't be handled, pass it to the callback and return.
Must not throw. Return value ignored.
return x ==> return cb(null, x)
throw er ==> return cb(er)
// return true if a path is either// a symlink or a directory.functionisLinkOrDir(path,cb){fs.lstat(path,function(er,s){if(er)returncb(er)returncb(null,s.isDirectory()||s.isSymbolicLink())})}
asyncMap
Usecases
I have a list of 10 files, and need to read all of them, and then continue when they're all done.
I have a dozen URLs, and need to fetch them all, and then continue when they're all done.
I have 4 connected users, and need to send a message to all of them, and then continue when that's done.
I have a list of n things, and I need to dosomething with all of them, in parallel, and get the results once they're all complete.