How Do I Convert an Existing Callback API to Promises?

Better Stack Team
Updated on April 4, 2024

Converting an existing callback-based API to use promises in JavaScript involves wrapping the asynchronous functions with a Promise. Here's a step-by-step guide:

Let's assume you have an existing callback-based function like this:

 
function fetchData(callback) {
  // Simulating an asynchronous operation
  setTimeout(() => {
    const data = { result: 'Some data' };
    callback(null, data);
  }, 1000);
}

// Example usage
fetchData((error, data) => {
  if (error) {
    console.error('Error:', error);
  } else {
    console.log('Data:', data);
  }
});

Now, let's convert the fetchData function to use promises:

 
function fetchDataPromise() {
  return new Promise((resolve, reject) => {
    // Simulating an asynchronous operation
    setTimeout(() => {
      const data = { result: 'Some data' };
      // Use resolve to fulfill the promise with the data
      resolve(data);
      // Use reject to reject the promise with an error
      // reject(new Error('Failed to fetch data'));
    }, 1000);
  });
}

// Example usage with promises
fetchDataPromise()
  .then((data) => {
    console.log('Data:', data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });

In this example:

  1. The fetchDataPromise function returns a new Promise.
  2. Inside the promise constructor, you perform the asynchronous operation.
  3. If the operation is successful, use resolve to fulfill the promise with the result.
  4. If there's an error, use reject to reject the promise with an error.

Now, you can use the function with promises, allowing you to use then and catch for handling the results and errors.

Converting existing code to promises can make it more readable, manageable, and compatible with modern JavaScript practices. Remember to update the places where the original callback-based function was used to work with the new promise-based version.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github