Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Refactoringbeginner

Callback to Promise

Share

Convert callback-based code to Promises

Works with OpenClaude

You are a JavaScript refactoring specialist. The user wants to convert callback-based asynchronous code to Promise-based code.

What to check first

  • Identify all callback functions that follow the error-first callback pattern (error as first argument)
  • Check if the codebase already uses Promises elsewhere to match style consistency
  • Verify the Node.js version supports Promises natively (4.0+) or if a polyfill is needed

Steps

  1. Locate callback-based functions that accept a callback as the last parameter, typically with (err, result) => {} signature
  2. Wrap the callback function body in a new Promise((resolve, reject) => {}) constructor
  3. Replace callback invocations with resolve(value) for success paths and reject(error) for error paths
  4. Change the function signature from function(params, callback) to function(params) and add return before the Promise
  5. Update all calling code to use .then(result => {}) and .catch(error => {}) or await syntax
  6. Test that error cases properly reject and flow to .catch() or the catch block in try/await
  7. Remove the callback parameter completely from the function definition
  8. Verify all chained .then() calls properly return values for downstream handlers

Code

// BEFORE: Callback-based
function fetchUser(userId, callback) {
  setTimeout(() => {
    if (userId > 0) {
      callback(null, { id: userId, name: 'John' });
    } else {
      callback(new Error('Invalid user ID'));
    }
  }, 1000);
}

fetchUser(1, (err, user) => {
  if (err) {
    console.error('Error:', err.message);
  } else {
    console.log('User:', user);
  }
});

// AFTER: Promise-based
function fetchUser(userId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (userId > 0) {
        resolve({ id: userId, name: 'John' });
      } else {
        reject(new Error('Invalid user ID'));
      }
    }, 1000);
  });
}

// Using .then/.catch
fetchUser(1)
  .then(user => console.log('User:', user))
  .catch(err => console.error('Error:', err.message));

// Using async/await
async function loadUser() {
  try {
    const user = await fetchUser(1);
    console.log('User:', user);
  } catch (err) {
    console.error('Error:', err.message);
  }
}

loadUser();

Pitfalls

  • Don't forget to return the Promise — without return, the function returns undefined and callers can't chain .then()
  • Error-first callback pattern is critical — if error is second parameter instead

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryRefactoring
Difficultybeginner
Version1.0.0
AuthorClaude Skills Hub
refactoringcallbackspromises

Install command:

curl -o ~/.claude/skills/callback-to-promise.md https://claude-skills-hub.vercel.app/skills/refactoring/callback-to-promise.md

Related Refactoring Skills

Other Claude Code skills in the same category — free to download.

Want a Refactoring skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.