Blog>
Snippets

Refactoring Callbacks to Promises

Show how to refactor legacy JavaScript callback-based asynchronous code to modern Promises for better readability and error handling.
// Given legacy async function with a callback
function fetchData(callback) {
  setTimeout(() => {
    try {
      // Simulate fetched data
      const data = 'sample data';
      // Call the callback with null error and data
      callback(null, data);
    } catch (error) {
      // Call the callback with an error and no data
      callback(error);
    }
  }, 1000);
}

// Refactored function returning a Promise
function fetchDataPromise() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        // Simulate fetched data
        const data = 'sample data';
        // Resolve the promise with data
        resolve(data);
      } catch (error) {
        // Reject the promise with an error
        reject(error);
      }
    }, 1000);
  });
}

// Using the refactored function
fetchDataPromise()
  .then(data => console.log('Data received:', data))
  .catch(error => console.error('Error fetching data:', error));
This refactoring replaces a callback-style asynchronous function with a Promise-based one. The original function 'fetchData' takes a callback which is called with an error or data. The refactored version, 'fetchDataPromise', returns a new Promise that resolves with data or rejects with an error. The usage of the refactored function shows the 'then' method for handling resolved values and the 'catch' method for handling errors, leading to clearer and more maintainable code.