Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including promised-node with all npm packages installed. Try it out:

var promisedNode = require("promised-node")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

promised-node v0.1.4

Allow loading existing node modules with callbacks as promises modules.

promised-node

Allow loading existing node modules with callbacks as promises modules.

How it works is by scanning the module for functions that have the same name also with a Sync suffix (e.g. readdir and readdirSync), and then replaces them with a function that doesn't have the last callback parameter, but instead returns a promise.

Promises are fully conformant to the APlus promises spec: https://github.com/promises-aplus/promises-spec

Here is an example:

var fs = require("promised-node").load("fs");

fs.readdir(".").then(function(files) {
    files.forEach(function(name) {
        console.log(name);
    });
});

If the callback method receives multiple arguments, they will be sent into an Array into the fulfillment of the promise:

var fs = require("promised-node").load("fs");

var fd;

fs.open("test.txt", "w").then(function(_fd) {         // open the file
    fd = _fd;
    return fs.write(fd, new Buffer("test"), 0, 4, 0); // write 4 bytes
}).then(function(data) {
    console.log("written: ", data);
    return fs.close(fd);                              // close the file
}).then(null, function(e) {
    console.log("Something terrible happened: ", e);
});

As you can notice, since now we're using promises, writing async code becomes far simpler now.

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free