Last active
December 24, 2015 11:39
-
-
Save radiosilence/6792343 to your computer and use it in GitHub Desktop.
A faster pattern of doing chained/changeable sequences and flattening out callback hell.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = | |
errback: (cargs..., {callbacks, error: [eb, args...]}) -> | |
eb(args..., cargs..., {callbacks: callbacks, error: [eb, args...]}) | |
callback: (cargs..., {callbacks, error}) -> | |
[cb, args...] = callbacks.shift() | |
cb(args..., cargs..., {callbacks: callbacks, error: error}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http = require 'http' | |
pg = require('pg').native | |
{errback, callback} = require('./chains.coffee') | |
conString = "postgres://qrs:qrs@localhost/qrs" | |
reportError = (res, err, chains) -> | |
res.writeHead 500, | |
'content-type': 'application/json' | |
res.end JSON.stringify err | |
getClient = (chains) -> | |
pg.connect conString, (err, client, done) -> | |
if err | |
return errback(args, err, chains) | |
callback(client, done, chains) | |
doQuery = (query, client, done, chains) -> | |
client.query query, (err, result) -> | |
if err | |
return errback(err, chains) | |
done() | |
callback(result.rows, chains) | |
respond = (res, data, chains) -> | |
res.writeHead 200, | |
'content-type': 'application/json' | |
res.end JSON.stringify data | |
httpServer = http.Server (req, res) -> | |
getClient | |
callbacks: [ | |
[doQuery, 'SELECT id FROM instruments_instrument LIMIT 5'] | |
[respond, res] | |
] | |
error: [reportError, res] | |
httpServer.listen 1337 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment