Skip to content

Instantly share code, notes, and snippets.

@glenjamin
Last active December 27, 2015 12:29
Show Gist options
  • Save glenjamin/7326445 to your computer and use it in GitHub Desktop.
Save glenjamin/7326445 to your computer and use it in GitHub Desktop.
How to optimise callbacks that need state
var app = express();
database.connect(function(err, db) {
app.db = db;
app.listen(1337);
})
app.get('/stuff/:id', stuffHandler);
function stuffHandler(req, res) {
app.db.fetch(req.params.id, function datastoreCallback(err, data) {
res.send(data);
})
}
// How do I perform an action on `res` without creating a new function on each request?
@glenjamin
Copy link
Author

For anyone following on at home, the answer is that ideally the callback API should provide something like:

db.fetch(id, callback, context, arg0, arg1, arg2)

// Uses `id` to calculate `result`, then calls back:

callback.call(context, result, arg0, arg1, arg2)

Much like the javascript built-in setTimeout https://developer.mozilla.org/en/docs/Web/API/window.setTimeout#Syntax

This would allow me to do:

app.db.fetch(req.params.id, stuffRenderer, res)
function stuffRenderer(err, stuff, res) {
    res.send(stuff);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment