1.0.0 • Published 8 years ago

babel-promisify v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
8 years ago

babel-promisify

Build Status Coverage Status npm version npm downloads Gitter chat

Converts callback-based functions to Babel or Native Promises. This module is babel port of es6-promisify.

Install

Install with npm

npm install --save babel-promisify

Example

"use strict";

// Declare variables
var promisify = require("babel-promisify"),
    fs = require("fs"),

// Convert the stat function
    stat = promisify(fs.stat);

// Now usable as a promise!
stat("example.txt").then(function (stats) {
    console.log("Got stats", stats);
}).catch(function (err) {
    console.error("Yikes!", err);
});

Provide your own callback

"use strict";

// Declare variables
var promisify = require("babel-promisify"),
    fs = require("fs"),
    stat;

// Convert the stat function, with a custom callback
stat = promisify(fs.stat, function (err, result) {
    if (err) {
        console.error(err);
        return this.reject("Could not stat file");
    }
    this.resolve(result);
});

stat("example.txt").then(function (stats) {
    console.log("Got stats", stats);
}).catch(function (err) {
    // err = "Could not stat file"
});

Promisify methods

"use strict";

// Declare variables
var promisify = require("babel-promisify"),
    redis = require("redis").createClient(6379, "localhost"),

// Create a promise-based version of send_command
    client = promisify(redis.send_command.bind(redis));

// Send commands to redis and get a promise back
client("ping", []).then(function (pong) {
    console.log("Got", pong);
}).catch(function (err) {
    console.error("Unexpected error", err);
}).then(function () {
    redis.quit();
});

Tests

Test with mocha & chai

$ npm test

Published under the MIT License.