0.1.0 • Published 5 years ago

@ctheory/promisify v0.1.0

Weekly downloads
1
License
MIT
Repository
-
Last release
5 years ago

@ctheory/promisify npm.io npm (scoped) npm type definitions

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
  });