Convert callback-based javascript to ES6 Promises (Evacuated from Microsoft Github)
Mike Hall 0de94e02cc 6.0.0 | 6 years ago | |
---|---|---|
dist | 6 years ago | |
lib | 6 years ago | |
test | 6 years ago | |
.babelrc | 6 years ago | |
.eslintrc.yml | 6 years ago | |
.gitignore | 6 years ago | |
.travis.yml | 6 years ago | |
LICENSE | 6 years ago | |
README.md | 6 years ago | |
package-lock.json | 6 years ago | |
package.json | 6 years ago |
Converts callback-based functions to ES6/ES2015 Promises, using a boilerplate callback function.
Install with npm
npm install es6-promisify
const {promisify} = require("es6-promisify");
// Convert the stat function
const fs = require("fs");
const 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);
});
const {promisify} = require("es6-promisify");
// Create a promise-based version of send_command
const redis = require("redis").createClient(6379, "localhost");
const 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();
});
const {promisify} = require("es6-promisify");
function test(cb) {
return cb(undefined, 1, 2, 3);
}
// Create promise-based version of test
test[promisify.argumentNames] = ["one", "two", "three"];
const multi = promisify(test);
// Returns named arguments
multi().then(result => {
console.log(result); // {one: 1, two: 2, three: 3}
});
const {promisify} = require("es6-promisify");
// Now uses Bluebird
promisify.Promise = require("bluebird");
const test = promisify(cb => cb(undefined, "test"));
test().then(result => {
console.log(result); // "test", resolved using Bluebird
});
Test with tape
$ npm test
Promise
Promise
. If your environment has no native Promise
you must polyfill yourself, or set promisify.Promise
to an A+ compatible Promise
implementation.settings.thisArg
: use .bind()
instead.settings.multiArgs
: use named arguments instead.Published under the MIT License.