Given promises are present in 0.12.* (which is cool), and that the API remains the same in 0.12 and remains in its nodeback form (which is cool, and I completely agree with). I'd like to propose a utility method to interop between promises and nodebacks.
No changes need to be made to any APIs, all NodeJS APIs remain with nodebacks (which, I'm all for). In my opinion, it should be very easy for a developer to choose which method of asynchronousity they prefer and move back and forth between promises and nodebacks.
util.promisify(fn) - takes a function whose last argument is in the form of function(err,result){ and returns a new function that does exactly the same as fn but returns a promise.
So, something like:
var fs = require("fs");
var readFileAsync = util.promisify(fs.readFile);
readFileAsync().then(function(contents){
// contents of file available here
}).catch(function(err){
// handle error from .then, or I/O error here
});
You can see for example @petkaantonov 's Promise.promisify function and what it does. Note that it works with almost 0 overhead.
I'd also like to propose a util.nodeify function (needs a better name) that takes a promise, and returns a node callback version of it. This way, people who have to use promisified modules can get callbacks instantly:
var apiCall = util.nodeify(promiseCall);
apiCall(function(err,result){
// err and result here are defined in the node convention
});
What are your opinions about this? Would a PR be entertained?
Given promises are present in 0.12.* (which is cool), and that the API remains the same in 0.12 and remains in its nodeback form (which is cool, and I completely agree with). I'd like to propose a utility method to interop between promises and nodebacks.
No changes need to be made to any APIs, all NodeJS APIs remain with nodebacks (which, I'm all for). In my opinion, it should be very easy for a developer to choose which method of asynchronousity they prefer and move back and forth between promises and nodebacks.
util.promisify(fn) - takes a function whose last argument is in the form of
function(err,result){and returns a new function that does exactly the same asfnbut returns a promise.So, something like:
You can see for example @petkaantonov 's
Promise.promisifyfunction and what it does. Note that it works with almost 0 overhead.I'd also like to propose a
util.nodeifyfunction (needs a better name) that takes a promise, and returns a node callback version of it. This way, people who have to use promisified modules can get callbacks instantly:What are your opinions about this? Would a PR be entertained?