#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Asynchronous JavaScript

Replacing Callbacks with Promises

Replacing callbacks with promises means taking a function that reports its result through a callback and wrapping it so that it returns a Promise instead. You do this when you want to chain steps with .then(), handle every failure in one .catch(), or use async/await with older APIs that were written before promises existed.

Wrapping a callback API by hand

The Promise constructor takes an executor function with two parameters, resolve and reject. Inside it you call the old callback-based function. When its callback fires, you call resolve with the result or reject with the error. This is often called "promisifying" a function.

const fs = require('fs');

function readText(path) {
  return new Promise((resolve, reject) => {
    fs.readFile(path, 'utf8', (err, text) => {
      if (err) {
        reject(err);
      } else {
        resolve(text);
      }
    });
  });
}

readText('config.json')
  .then((text) => JSON.parse(text))
  .then((config) => console.log('Port:', config.port))
  .catch((err) => console.error('Failed:', err.message));

Notice how the error handling moved. Instead of checking err in every nested callback, a single .catch() at the end handles a missing file and invalid JSON alike, because a thrown error inside .then() also rejects the chain.

Turning a timer into a promise

Browser APIs can be wrapped the same way. setTimeout has no error case, so you only need resolve:

const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function showSteps() {
  console.log('Saving...');
  await wait(1500);
  console.log('Saved!');
}

Once a function returns a promise, it works naturally with await, and the code reads from top to bottom like normal synchronous code.

Let Node do it: util.promisify and the promises API

You rarely need to write wrappers for Node core modules. Two built-in options exist:

  • util.promisify(fn) converts any function that follows the error-first callback pattern into one that returns a promise.
  • Many modules ship a promise version already, such as require('fs/promises') or require('timers/promises').

Prefer these over hand-written wrappers for core APIs. Write your own only for third-party code or browser APIs that have no promise version.

Pitfalls when converting

A few mistakes come up again and again:

  • Forgetting to return the promise. If your wrapper creates a promise but does not return it, callers receive undefined and cannot chain on it.
  • Never settling. If one branch of the callback calls neither resolve nor reject, the promise stays pending forever and nothing after it runs.
  • Resolving with an error. Calling resolve(err) instead of reject(err) makes a failure look like success, so your .catch() never fires.
  • Mixing styles. Passing a callback and also using the returned promise leads to the same work being handled twice. Pick one style per function.

Also remember that a promise settles only once. Calling resolve a second time is silently ignored, which protects you from the "callback fired twice" bug.

What you gain

After converting, sequential steps become a flat chain instead of a pyramid, errors travel to one place, and you can combine operations with helpers like Promise.all. The original API still does the real work; the promise is just a cleaner way of receiving its result.

Key point: wrap the callback once, call resolve or reject exactly once inside it, and from then on treat the function like any other promise-returning code.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course