Skip to content

Instantly share code, notes, and snippets.

@reu
Last active July 11, 2017 09:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reu/b052265483c1c6b18ff2 to your computer and use it in GitHub Desktop.
Save reu/b052265483c1c6b18ff2 to your computer and use it in GitHub Desktop.
Convert any NodeJS async function into a Promise
module.exports = function denodify(fn) {
return function() {
var self = this;
var args = Array.prototype.slice.call(arguments);
return new Promise(function(resolve, reject) {
args.push(function(error, result) {
error ? reject(error) : resolve(result);
});
fn.apply(self, args);
});
}
}
var fs = require("fs");
var denodify = require("denodify");
var co = require("co");
var readFile = denodify(fs.readFile);
co(function *() {
var hosts = yield readFile("/etc/hosts");
var passwd = yield readFile("/etc/passwd");
console.log("hosts:", hosts.toString());
console.log("passwd: ", passwd.toString());
});
var fs = require("fs");
var denodify = require("denodify");
var readFile = denodify(fs.readFile);
readFile("./denodifys.js")
.then(function(file) { return file.toString() })
.then(function(file) {
return file.length > 5 ? Promise.reject("Arquivo muito pequeno") : file.length;
})
.then(console.log, console.error)
Promise.all([readFile("/etc/hosts"), readFile("/etc/passwd")]).then(function(files) {
var hosts = console.log("hosts:", files[0].toString());
var passwd = console.log("passwd:", files[1].toString());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment