Last active
July 11, 2017 09:41
-
-
Save reu/b052265483c1c6b18ff2 to your computer and use it in GitHub Desktop.
Convert any NodeJS async function into a Promise
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
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); | |
}); | |
} | |
} |
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 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()); | |
}); |
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 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