@ctheory/promisify
v0.1.0
Published
Promisify callback based functions
Downloads
14
Readme
@ctheory/promisify
A simple TS typed function for promisifying callback based functions.
Usage
async
/await
syntax
import promisify from '@ctheory/promisify';
const callbackFunction = (arg1, arg2, callback) => {
if (arg1 && arg2) {
callback(null, 'Success');
} else {
callback(new Error('An error happened'));
}
};
const promisedFunction = promisify(callbackFunction);
try {
const result = await promisedFunction('arg1', 'arg2');
// Use result as usual
} catch (err) {
// Callbacks are assumed to use error first convention
// The error will be thrown if present
console.log('callbackFunction failed with an error', err);
}
Promise
syntax
const promisedFunction = promisify(callbackFunction);
promisedFunction
.then(result => {
// Use the result
})
.catch(err => {
// Handle the thrown error
});