#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

Patterns for Dealing with Asynchronous Code

JavaScript runs your code on a single thread, so any work that takes time, such as a network request, a timer or reading a file in Node, has to report back later instead of blocking everything. Over time the language has gained three main patterns for handling that "later": callbacks, promises and async/await. Knowing all three helps you read older code, work with any library and pick the right tool for new code.

Pattern one: callbacks

A callback is a function you pass to another function so it can be called when the work finishes. Browser APIs such as setTimeout and addEventListener use this style, and older Node APIs follow an "error-first" convention where the first argument is an error or null.

const fs = require('fs');

fs.readFile('notes.txt', 'utf8', (err, text) => {
  if (err) {
    console.error('Read failed:', err.message);
    return;
  }
  console.log(text.length, 'characters read');
});

Callbacks are simple, but they get awkward when steps depend on each other. Each step nests inside the previous one, and error checks repeat at every level.

Pattern two: promises

A promise is an object that stands for a value that is not ready yet. It starts as pending and later becomes either fulfilled with a value or rejected with a reason. You attach handlers with .then() and .catch(), and because .then() returns a new promise, steps can be chained in a flat line instead of nesting.

Promises also give you helpers for groups of tasks: Promise.all, Promise.allSettled, Promise.race and Promise.any.

Pattern three: async and await

This is syntax built on top of promises. An async function returns a promise, and await pauses that function until a promise settles. The same chain you wrote with .then() can be written as straight-line code with ordinary try...catch.

const fs = require('fs/promises');

async function countWords(path) {
  try {
    const text = await fs.readFile(path, 'utf8');
    return text.split(/\s+/).filter(Boolean).length;
  } catch (err) {
    console.error('Could not count words:', err.message);
    return 0;
  }
}

Comparing the three side by side

PatternGood forWatch out for
CallbacksEvents that fire many times, simple one-off timersDeep nesting, forgetting to handle the error argument
PromisesChaining steps, combining several tasksForgetting to return inside .then(), missing .catch()
Async/awaitReadable sequences of dependent stepsAwaiting independent tasks one by one, slowing things down

A mistake people make when mixing patterns

Trouble often starts when a callback API is used inside promise code without converting it. If you call a callback-style function inside an async function, await has nothing to wait for, and the function returns before the work is done. Convert the API first. In Node you can use util.promisify or the built-in promise versions such as fs/promises. In the browser you can wrap a callback in new Promise((resolve, reject) => ...).

The reverse problem also appears: a promise created inside an event handler with no .catch() produces an "unhandled rejection" warning and the error goes unnoticed. Every promise chain needs an end point that handles failure.

Choosing a pattern

Keep callbacks for events that repeat, like clicks or stream data. Use promise helpers when you need to coordinate several tasks at once. Use async/await for most everyday sequences, because it reads top to bottom and handles errors the same way as synchronous code. Under the hood, async/await and promises are the same mechanism, so you can mix them freely once callback APIs are converted.

Ready to master real-world web development?

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

Explore Course