1.0.0 • Published 5 years ago

promisify-cb v1.0.0

Weekly downloads
2
License
ISC
Repository
-
Last release
5 years ago

Promisify

A simple javascript module that dynamically provides promise and callback supports for code that must be executed asyncronously.

Promisify(execute, callback)

ParameterTypeRequiredDescription
executefunctionYesThe function which returns and errors must be respectively resolved and rejected in a Promise. execute can return a Promise.
callbackfunctionNoIf provided Promisify returns a null and errors and returns are passed to the callback.

Callback

It uses the following signature callback(err, result). If any error is thrown during the execution of execute is catched and passed as a err. Any return of the execute is passed as result.

Return

Returns a Promise if no callback is provided and return null if callback is provided.

Usage

const Promisify = require('Promisify');

const execute = function() {
    // stuff
    if (condition)
        throw new SomeError();
    return result;
}

Promisify(execute, callback);
// if callback is null or undefined returns a Promise that resolves in result or is rejected with an instance of SomeError

Example

// Instead of...
async function f1(param, cb) {
    let err = null;
    const result = true;
    if (!param)
        err = new Error();
    if (!cb) {
        throw err;
    } else
        cb(err, result);
    return result;
}

// ...you can use:
function f2(param, cb) {
    return Promisify(() => {
        if (!param)
            throw new Error();
        return true;
    }, cb);
}

// or you can handle errors on the provided parameters in a easier way:
function f2(param, cb) {
    if (!param)
        throw new Error();
    return Promisify(() => {
        return true;
    }, cb);
}
// in this way no promise rejection will be thrown.