Sample code to wrap JS callbacks into Promises

By | March 10, 2020

As any JavaScript developer knows, some built in Browser provided methods (or methods provided through Node.JS) have not been converted to Promises and still use the old callback method, quickly leading to callback hell.

You can use this code to wrap any callback method into a Promise, then use your Promise function instead of the old callback method, allowing you to chain Promises using .then() and other beneficial methods. In this example I will use the navigator.geolocation.getCurrentPosition() method.

Start by creating your own method that takes in one optional argument. This will be used to pass into the third parameter navigator.geolocation.getCurrentPosition() accepts. The first two parameters are the success and error callbacks which will be replaced via the Promise. In this example, my new “replacement method” will be named getPosition:

const getPosition = opts => {
  const promise = new Promise((resolve, reject) => {});
  return promise;
};

Note, the code above can be used to wrap ANY standard callback method. You may need to add parameters if the callback method expects additional parameters. Now, lets add our “legacy” callback method.

const getPosition = opts => {
  const promise = new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      success => {},
      error => {},
      opts,
    );
  });
  return promise;
};

Next, we need to base our promise resolution or rejection into what the original callback function would expect for its success or error callback functions. That can be done like so:

const getPosition = opts => {
  const promise = new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(
      success => {
        resolve(success);
      },
      error => {
        reject(error);
      },
      opts,
    );
  });
  return promise;
};

This then allows you to call getPosition() as a Promise instead of navigator.geolocation.getCurrentPosition() as a callback, allowing you to to chain together Promises in a much cleaner way using the built in Promise methods.