#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

Async and Await

async and await are keywords that let you write promise-based code so it reads like ordinary top-to-bottom code. You mark a function with async, and inside it you put await in front of any promise to pause that function until the promise settles. You reach for them whenever you fetch data, read files, wait on a timer or chain several asynchronous steps that depend on each other.

What the async keyword changes

An async function always returns a promise, even if you return a plain value. Writing return 5 inside it is the same as returning Promise.resolve(5). If the function throws, the returned promise is rejected with that error. This means callers can use .then() on it or await it from another async function.

You can apply async to function declarations, function expressions, arrow functions and class methods. In JavaScript modules (files loaded with type="module" or .mjs files in Node), you can also use await at the top level without wrapping it in a function.

How await pauses only one function

When the engine reaches await somePromise, it suspends the current async function and hands control back to the event loop. Other code, click handlers and timers keep running. When the promise fulfils, the function resumes on the next line and await evaluates to the fulfilled value. Nothing about the browser freezes; only that one function is waiting.

async function loadUser(id) {
  try {
    const response = await fetch(`/api/users/${id}`);
    if (!response.ok) {
      throw new Error(`Request failed with status ${response.status}`);
    }
    const user = await response.json();
    console.log(user.name);
    return user;
  } catch (error) {
    console.error('Could not load user:', error.message);
    return null;
  }
}

loadUser(7).then((user) => console.log('Done', user));

Notice that fetch does not reject on a 404 or 500 status. It only rejects on network failure, so the code checks response.ok and throws on its own.

Error handling with try and catch

A rejected promise that you await behaves like a thrown exception at that line. That is why try...catch works naturally here, and why a finally block is a clean place to hide a loading spinner whether the request succeeded or not. If you do not catch the error, the promise returned by your async function rejects, and the caller must handle it.

The sequential await trap

The most common mistake is awaiting independent tasks one after another. Each await waits for the previous one to finish, so two requests that each take one second end up taking two seconds in total.

// Slow: the second request starts only after the first finishes
const posts = await fetch('/api/posts').then((r) => r.json());
const tags = await fetch('/api/tags').then((r) => r.json());

// Faster: start both, then wait for both together
const [postsData, tagsData] = await Promise.all([
  fetch('/api/posts').then((r) => r.json()),
  fetch('/api/tags').then((r) => r.json()),
]);

This connects directly to running parallel promises: Promise.all still does the parallel work, and await simply waits for the combined result. Use Promise.allSettled when you want every result even if some fail.

Another slip is calling await inside array.forEach(). The forEach callback does not wait, so the loop finishes before any of the work does. Use a for...of loop when steps must run in order, or Promise.all with map when they can run together.

Quick reference

  • async makes a function return a promise automatically.
  • await only works inside async functions or at the top level of a module.
  • Wrap awaited calls in try...catch to handle rejections.
  • Await independent tasks together with Promise.all, not one by one.
  • Avoid await inside forEach; use for...of instead.

Ready to master real-world web development?

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

Explore Course