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.