Git Product home page Git Product logo

es6-promisify's Introduction

Build Status

es6-promisify

Converts callback-based functions to Promises, using a boilerplate callback function.

Install

Install with npm

npm install es6-promisify

Example

const {promisify} = require("es6-promisify");

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

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

Promisify methods

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
try {
    const pong = await client.ping();
    console.log("Got", pong);
} catch (err) {
    console.error("Unexpected error", err);
} finally {
    redis.quit();
}

Handle multiple callback arguments, with named parameters

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
const result = await multi();
console.log(result); // {one: 1, two: 2, three: 3}

Provide your own Promise implementation

const {promisify} = require("es6-promisify");

// Now uses Bluebird
promisify.Promise = require("bluebird");

const test = promisify(cb => cb(undefined, "test"));
const result = await test();
console.log(result); // "test", resolved using Bluebird

Tests

Test with tape

$ npm test

Published under the MIT License.

es6-promisify's People

Contributors

dependabot[bot] avatar greenkeeperio-bot avatar miguelsm avatar mikehall314 avatar pgaubatz avatar poying avatar rysenko avatar trysound avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

es6-promisify's Issues

does not work with class methods

This is the problem:
https://github.com/digitaldesignlabs/es6-promisify/blob/master/lib/promisify.js#L63

If you pass in a class method, that is used in apply instead of the original class instance.

I solved it by passing class instance and method name separately, e.g. promisify(someClass, 'someMethod') and modify promisify.js to

    return function (that, methodName, custom) {

        return function () {
            for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
                args[_key3] = arguments[_key3];
            }

            // Return the promisified function
            return new ES6Promise(function (resolve, reject) {

                // Create a Context object
                var ctx = new Context(resolve, reject, custom);

                // Append the callback bound to the context
                args.push(callback.bind(null, ctx));

                // Call the function
                that[methodName].apply(that, args);
            });
        };
    };

But that is a change in API. What do you suggest? Overload promisify and detect if second parameter is either a string or custom callback?

Deploy on Azure failed

Hi,

I have a problem when I deploy my angular app with your package:
npm install
npm ERR! path D:\home\site\repository\src\client\node_modules.staging\npm-d4c06741\node_modules\libnpmhook\node_modules\npm-registry-fetch\node_modules\make-fetch-happen\node_modules\http-proxy-agent\node_modules\agent-base\node_modules\es6-promisify\node_modules\es6-promise
npm ERR! code EINVAL
npm ERR! errno -4071
npm ERR! syscall rename
npm ERR! EINVAL: invalid argument, rename 'D:\home\site\repository\src\client\node_modules.staging\npm-d4c06741\node_modules\libnpmhook\node_modules\npm-registry-fetch\node_modules\make-fetch-happen\node_modules\http-proxy-agent\node_modules\agent-base\node_modules\es6-promisify\node_modules\es6-promise' -> 'D:\home\site\repository\src\client\node_modules.staging\es6-promise-3ac93eae'

The problem is due to Azure who have issue to rename long path, Is there a way on your side to help me to fix this issue?

Probably not, but I tried so many different solutions which didnt work that now, I try other possibilities.

Thanks

Bundling a promise polyfill is not optimal

Currently this library checks to see if there is a Promise global defined and if there is not then it specifically requires() 'es6-promise'. The problem with this is that there are a bunch of Promise polyfills out there that people use. If using this library with a bundler like webpack, that require call is going to always include 'es6-promise' even if Promises have already been polyfilled elsewhere, resulting in size bloat of the bundle.

Would it be possible instead to just assume "Promise" exists and include instructions on the possible necessity of polyfilling with an example of how to do so? This would give users a lot more flexibility.

Document a callback with multiple arguments

It would be nice to document what happens when you promisify a node function with a callback that takes multiple arguments. Here is an ES6 example you could maybe use:

import tmp from 'tmp';  // node builtin

let createTmpDir = promisify(tmp.dir);
createTmpDir()
  .then((args) => {
    let [tmpPath, removeTmpDir] = args;
    // ...
  });

For those unfamiliar with promises, they would expect it to look more like:

createTmpDir()
  .then((tmpPath, removeTmpDir) => {
    // ...
  });

Allow promisifying methods (not just functions)

promisify binds the receiver explicitly, but what if we would like to call the promisified function with different receivers?

As a workaround, I use this function:

function promisify_unbound(f) {
    let flat = promisify(function(self, ...args) { return f.apply(self, args) })
    return function(...args) { return flat(this, ...args) }
}

But maybe there should be built-in support for this?

Please add LICENSE file

The MIT license specifically states that the license text must accompany the source code. Will you please add a LICENSE file with your copyright information and the text of the MIT license? Thanks!

Remove "own resolver" functionality

Currently, es6-promisify allows you to supply your own resolver function. This adds quite a bit of complexity and indirectness to the library. But if you want to provide your own resolver, this is trivial with new Promise().

Propose that the custom resolver function is removed, and the second argument is used to pass in a thisArg, instead of requiring the use of .bind()

Feature request: Promise.promisifyAll()

Hi,

I've got a (small) feature request.
Namely, it would be nice if there was Promise.promisifyAll() (like the one available in Bluebird, see API) available...

Cheers,
Patrick

Minify bundle.

I have a suggestion to minify bundle. At least strip comments, to make it smaller. What do you think regarding this?

In any case thank you for your work.

Invalid assignment error.

Failed to compile.

static/js/main.d834a8b4.js from UglifyJs
Invalid assignment [./~/promisify-es6/index.js:26,0][static/js/main.d834a8b4.js:2961,41]


npm ERR! Darwin 16.6.0
npm ERR! argv "/Users/niksair/.nvm/versions/node/v7.8.0/bin/node" "/Users/niksair/.nvm/versions/node/v7.8.0/bin/npm" "run" "build"
npm ERR! node v7.8.0
npm ERR! npm  v4.2.0
npm ERR! code ELIFECYCLE
npm ERR! errno 1

Is this package specific?

Unable to promisify localStorage

Hi,
I want to promisify the localStorage object.

using like this -
const get = promisify(localStorage.getItem)

Can you tell me what i am doing wrong ?

Thank you

Consider faster promisification

Currently this package is very slow compared to promisification functions of libraries like Bluebird that utilize dynamic compilation techniques in order to achieve almost 0 overhead in performance.

Are there any plans on making this library fast?

Does not work on iOS9 safari

I am getting a strange error from this lib while using it with react native and iOS 9 devices.

globalObject.hasOwnProperty is not a function. (In 'globalObject.hasOwnProperty('Promise')', 'globalObject.hasOwnProperty' is undefined)

any ideas?!

Cannot read property 'apply' of undefined

I am getting an error
TypeError: Cannot read property 'apply' of undefined at D:\VS\WEB\Learn-Node\starter-files\node_modules\es6-promisify\dist\promisify.js:75:41

// routes
router.post('/register',
userController.validateRegister,
catchErrors(userController.register),
);

// for try and catch
exports.catchErrors = (fn) => {
return function (req, res, next) {
return fn(req, res, next).catch(next);
};
};

// controller
const promisify = require('es6-promisify');
....
....
exports.register = async (req, res, next) => {
const user = new User({ email: req.body.email, name: req.body.name });
const register = promisify(User.register, User);
await register(user, req.body.password);
res.send('it works');
next();
};

I am using "es6-promisify": "5.0.0"

Promises with multiple arguments group args into an array

As by design in #9, promisified functions that invoke a callback with multiple arguments are resolved as an array. This handling is confusing and unnecessary, as functions already accept more than one argument.

function example(callback) {
  return callback(error, 'a', 'b');
}

promisify(example)().then(result =>
  // result -> ['a', 'b']
);

// I would expect:
promisify(example)().then((a, b) =>
  // a -> 'a'
  // b -> 'b'
);

This is how Bluebird's promisify works, and means that the callback handler is invoked consistently regardless of the number of arguments returned.

Happy to provide a PR to fix this.

Breaks `this`

If I try to promisify this function:

WebpackDevServer.prototype.listen = function() {
    var listeningApp = this.listeningApp =
        this.app.listen.apply(this.app, arguments);
    this.io = socketio.listen(listeningApp, {
        "log level": 1
    });
    this.io.sockets.on("connection", function(socket) {
        if(this.hot) socket.emit("hot");
        if(!this._stats) return;
        this._sendStats(socket, this._stats.toJson());
    }.bind(this));
}

and then call it:

self.webpackDevServer.listen(
  settings.WEBPACK_PORT,
  settings.HOST
).then(
…

I get an error:

[TypeError: Cannot read property 'listen' of undefined]

However, I do not have this problem when I use prfun's implementation of promisify

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.