TypeOfNaN

Turning a Callback Function Into a Promise

Nick Scialli
December 29, 2020

New — Check out my free newsletter on how the web works!

Many utilities in JavaScript are readily available as functions that take callbacks. How easy is it to turn these into promises?

It turns out it’s pretty simple to do so on a case-by-case basis. Let’s look at one of the simpler built-in functions that take a callback function: setTimeout. Normally, setTimeout looks something like this:

const callback = function () {
  console.log('Just got called!');
};

setTimeout(() => {
  callback();
}, 1000);

(Note: I could have written this as setTimeout(callback, 1000) but think the longer form is clearer for explaining).

And 1000 ms later we see logged:

Just got called!

Let’s turn this into a promise right now. We can do this with the promise object.

function promiseTimeout(timeout) {
  return new Promise(function (res) {
    setTimeout(function () {
      res();
    }, timeout);
  });
}

And now we use it:

promiseTimeout(1000).then(function () {
  console.log('Just got called');
});

Of course, it’s more realistic to be in a scenario where your callback can have an error. A typical callback flow might look something like this:

someAsyncFunction(data, function (error, response) {
  if (error) {
    // Handle error here
  }
  // Handle response here
});

We can make this a promise too! The Promise object’s constructor function takes a second argument that handles rejection.

function someAsyncPromise(data) {
  return new Promise(function (res, rej) {
    someAsyncFunction(data, function (error, response) {
      if (error) {
        rej(err);
        return; // Make sure to return here or `res` will be called too!
      }
      res(response);
    });
  });
}

someAsyncPromise(myData)
  .then(function (response) {
    // Handle response here
  })
  .catch(function (error) {
    // Handle error here
  });

Of course, since our function returns a Promise, we can use async await!

async function myFunc() {
  try {
    const response = await someAsyncPromise(myData);
  } catch (error) {
    // Handle error here
  }
}

And there we have it. Go forth and covert thy callbacks to Promises!

🎓 Learn how the web works

One of the best ways to level up your tech career is to have a great foundational understanding of how the web works. In my free newsletter, How the Web Works, I provide simple, bite-sized explanations for various web topics that can help you boost your knowledge. Join 2,500+ other learners on the newsletter today!

Signing up is free, I never spam, and you can unsubscribe any time. You won't regret it!

Sign up for the newsletter »
Nick Scialli

Nick Scialli is a senior UI engineer at Microsoft.

© 2024 Nick Scialli