1.0.0 • Published 5 years ago
promisify-cb v1.0.0
Promisify
A simple javascript module that dynamically provides promise and callback supports for code that must be executed asyncronously.
Promisify(execute, callback)
Parameter | Type | Required | Description |
---|---|---|---|
execute | function | Yes | The function which returns and errors must be respectively resolved and rejected in a Promise . execute can return a Promise . |
callback | function | No | If 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.
1.0.0
5 years ago