node-callback-to-promise
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

node-callback-to-promise

NPM

Introduction

Encapsulate a method with a node-style callback in a Promise.

API

//
// encapsulate a method with a node-style callback in a Promise
//
// @param {function} fn        function to be encapsulated
// @param {object}   context   'this' of the encapsulated function
// @param {Array<any>} args    to be passed to the called function
//
// @return {Promise}           a Promise encapsulating the function
//
function promise(fn, context, args)

Install

npm install node-callback-to-promise

Usage

Suppose you provide an API with callback, but you also want to return Promise if caller not pass callback. callback-to-promise will help you in this scenario. Here is an example:

const callbackToPromise = require('node-callback-to-promise');

userSchema.methods.authenticate = function authenticate(plainTextPassword, callback) {
    if (!callback) {
        // if no callback, return a promise
        return callbackToPromise.promise(authenticate, this, [plainTextPassword]);
    }

    ...
}

References

Package Sidebar

Install

npm i node-callback-to-promise

Weekly Downloads

0

Version

2.0.1

License

MIT

Unpacked Size

3.86 kB

Total Files

4

Last publish

Collaborators

  • mingc