Skip to content
This repository was archived by the owner on Apr 22, 2023. It is now read-only.
This repository was archived by the owner on Apr 22, 2023. It is now read-only.

Add promisify method to util #7642

@benjamingr

Description

@benjamingr

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions