Created
December 3, 2012 02:52
-
-
Save alejandro/4192304 to your computer and use it in GitHub Desktop.
JS: Estilo Continuable (Control Flow)
This file contains 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
"use strict"; | |
var Continuable = {} | |
Continuable.make = function make(fn) { | |
if ('function' !== typeof(fn)) throw new Error(fn + 'is not a function') | |
var evnt; | |
function first() { | |
var args = [].slice.call(arguments) | |
return function callback(ok, bad) { | |
if (evnt) bad = evnt | |
else bad = function (err){ console.error(err.stack + '\n') } | |
args.push(function (err, fine){ | |
if (err) return bad(err) | |
ok(fine) | |
}) | |
return fn.apply(fn, args) | |
} | |
} | |
first.on = function (ev, dow) { if ('error' === ev) evnt = dow } | |
return first | |
} | |
Continuable.convert = function each(obj, things){ | |
if (typeof(obj) === 'object' && Array.isArray(obj)) { | |
return obj.map(Continuable.makeObject) | |
} | |
if (!things) things = [] | |
var fixed = {}, val | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key) && ~things.indexOf(key)){ | |
val = obj[key] | |
if (typeof(val) === 'function') { | |
fixed[key] = Continuable.make(val) | |
} else { | |
fixed[key] = val | |
} | |
} else fixed[key] = obj[key] | |
} | |
return fixed | |
} | |
module.exports = Continuable |
This file contains 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
var Continuable = require('./continuable') | |
function queryServer(query, db, cb) { | |
setTimeout(function (){ | |
cb(new Error('kas'), 'Query:' + query + ':' + db) | |
}, 1000) | |
} | |
queryServer = Continuable.make(queryServer) | |
queryServer('lolcats', 'gif')(function (dt){ | |
console.log('dt',dt) | |
}, function error(){ | |
console.log('un error ha ocurrido') | |
}) | |
// otro ejemplo, usando una librería del core | |
var fs = Continuable.convert(require('fs'), ['readFile']) | |
fs.readFile('./file.txt')(file, error) | |
function file (txt){ | |
console.log('El archivo es:', txt) | |
} | |
function error(){ | |
console.log('un error ha ocurrido') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment