Skip to content

Instantly share code, notes, and snippets.

@raynerpupo
Last active April 10, 2018 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raynerpupo/495d81245e16b708f39d6aaf1d597573 to your computer and use it in GitHub Desktop.
Save raynerpupo/495d81245e16b708f39d6aaf1d597573 to your computer and use it in GitHub Desktop.

Callbacks

Are basically functions that are called when some result is ready or they can also be used to signal errors.

function aDividedByB(a, b, onResultFn, onErrorFn) {
  if (b != 0) {
    return onResultFn(a / b);
  }
  return onErrorFn("The divisor can't be zero!");
}

In this example the function aDividedByB consumes some data in the first two parameters and decides if execute the success callback called onResultFn or call the fail callback with name onErrorFn.

A normal call to this function would be something like

aDividedByB(6, 3, console.log, console.error);

Promises

Are a way to pipe computations where you can have a resolve for valid results and a reject to break the pipe with some error.

Promisify

A promisify function converts some callback structured function into a Promise returning one where the success is mapped to resolve and the failure is mapped to reject.

There are many possible implementations of the promisify function due to the different ways that callback using functions can be written. For the previous structure for aDivededByB example, that is very common, the promisify function would be like:

function promisify(cbfn) {
  return (...args) => new Promise((resolve, reject) => {
    return cbfn(...args, resolve, reject);
  })
}

Since we are using rest parameters we could use this to promisify any function no matter the arity as long as it accepts the success and failure callbacks in the last two parameters.

Usage:

const promisedDivision = promisify(aDividedByB);
promisedDivision(6, 0)
  .then(res => console.log(`Result: ${res}`))
  .catch(err => console.log(`Error: ${err}`));

In this case it will enter the catch block since the reject function was called.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment