1 # After [![Build Status][1]][2]
3 Invoke callback after n calls
5 ## Status: production ready
10 var after = require("after")
11 var db = require("./db") // some db.
13 var updateUser = function (req, res) {
14 // use after to run two tasks in parallel,
15 // namely get request body and get session
16 // then run updateUser with the results
17 var next = after(2, updateUser)
20 getJSONBody(req, res, function (err, body) {
21 if (err) return next(err)
27 getSessionUser(req, res, function (err, user) {
28 if (err) return next(err)
35 function updateUser(err, result) {
38 return res.end("Unexpected Error")
41 if (!result.user || result.user.role !== "admin") {
43 return res.end("Permission Denied")
46 db.put("users:" + req.params.userId, result.body, function (err) {
49 return res.end("Unexpected Error")
62 var after = require("after")
63 , next = after(3, logItWorks)
69 function logItWorks() {
70 console.log("it works!")
74 ## Example with error handling
77 var after = require("after")
78 , next = after(3, logError)
81 next(new Error("oops")) // logs oops
82 next() // does nothing
84 // This callback is only called once.
85 // If there is an error the callback gets called immediately
86 // this avoids the situation where errors get lost.
87 function logError(err) {
107 [1]: https://secure.travis-ci.org/Raynos/after.png
108 [2]: http://travis-ci.org/Raynos/after
109 [3]: http://raynos.org/blog/2/Flow-control-in-node.js
110 [4]: http://stackoverflow.com/questions/6852059/determining-the-end-of-asynchronous-operations-javascript/6852307#6852307
111 [5]: http://stackoverflow.com/questions/6869872/in-javascript-what-are-best-practices-for-executing-multiple-asynchronous-functi/6870031#6870031
112 [6]: http://stackoverflow.com/questions/6864397/javascript-performance-long-running-tasks/6889419#6889419
113 [7]: http://stackoverflow.com/questions/6597493/synchronous-database-queries-with-node-js/6620091#6620091
114 [8]: http://github.com/Raynos/iterators
115 [9]: http://github.com/Raynos/composite