Popular Searches
Popular Course Categories
Popular Courses

Promises & async/await

Promises & async/await

28 mins Modern JavaScript (ES6+)

Promises & async/await in React JS

Course: React JS Training

Topic: Promises & async/await

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why asynchronous JavaScript matters

JavaScript runs your code one line at a time on a single thread. If a line took a long time to finish — say, downloading data from a server — and JavaScript simply waited there, the whole page would freeze: no clicks, no scrolling, no updates. To avoid this, JavaScript handles slow work asynchronously: it starts the task, moves on, and comes back to finish the job when the result is ready.

Asynchronous work is everywhere in real projects:

  • fetching data from an API or a database
  • waiting for a timer or an animation to finish
  • reading a file or asking the user for camera access
  • saving to browser storage and confirming the save

For anyone heading into React, this topic is not optional. React applications constantly start a task, wait for it, and then update the screen with the result. Training and hiring guides for modern React work treat comfortable asynchronous JavaScript as assumed baseline knowledge — see, for example, this overview of what modern React roles expect you to already know.

Before promises existed, developers handled async results with callback functions — functions passed into another function to be called later. With several steps, callbacks nest inside callbacks, producing hard-to-read code known as callback hell. Promises and async/await were introduced to fix exactly this problem.

2. What a promise is, in simple words

A promise is a built-in JavaScript object that works like a receipt for a task still in progress. When you start a slow operation, you immediately get a promise back — a small object that says "your result does not exist yet, but it will arrive here". Later, the promise is either fulfilled with a value (success) or rejected with a reason (failure).

Think of ordering food at a busy counter. You pay and receive a token. That token is the promise: it is not the food, but it guarantees an outcome. You can sit down and check your messages while the kitchen works. Eventually the token turns into your order, or the staff tells you the dish is finished. You never had to stand at the counter blocking everyone behind you.

The three states of a promise

StateMeaningWhat it holds
pendingthe task is still runningnothing yet
fulfilledthe task succeededa value
rejectedthe task faileda reason (often an Error object or a message)

A promise that has finished — fulfilled or rejected — is called settled. A promise settles exactly once, and its state and value never change afterwards. That guarantee is what makes promises reliable to build on.

3. Key terms on this page

  • Executor — the function you pass to new Promise(); it performs the work.
  • resolve / reject — the two functions the executor receives; calling one settles the promise.
  • Handler — a function attached with then, catch or finally that runs when the promise settles.
  • Chaining — connecting steps by returning values or promises from one then to the next.
  • async function — a function declared with the async keyword; it always returns a promise and allows await inside.
  • await — pauses an async function until a promise settles, then hands you the value.
  • Microtask queue — the waiting area where promise handlers line up before running.
  • Combinators — methods like Promise.all that run several promises together.

4. Creating a promise

The syntax

const promise = new Promise((resolve, reject) => {
  // ... do the work here ...

  // on success:
  resolve(value);

  // on failure:
  reject(error);
});

new Promise() takes one function, called the executor. The executor receives two functions, traditionally named resolve and reject:

  • resolve(value) marks the promise as fulfilled with that value.
  • reject(reason) marks it as rejected with that reason.

Three rules matter:

  1. The executor runs immediately and synchronously when new Promise() is called — not later.
  2. Calling resolve or reject settles the promise; the first call wins and later calls are ignored.
  3. Normally you return the promise so the caller can attach handlers to it.

A first example

const coinToss = new Promise((resolve, reject) => {
  const won = Math.random() > 0.5;

  if (won) {
    resolve("You won the toss");
  } else {
    reject("You lost the toss");
  }
});

At this moment the toss has already happened, but we have not yet said what to do with the outcome. That is the next step: attaching handlers.

5. Reading results with then

then attaches a handler that runs when the promise fulfills. The value passed to resolve becomes the argument of your function.

const order = new Promise((resolve) => {
  setTimeout(() => resolve("Pizza is ready"), 1000);
});

order.then((message) => console.log(message));

console.log("Order placed");

Output:

Order placed
Pizza is ready

Notice the order. "Order placed" prints first even though it is written last, because the promise needed one second. The program did not freeze while waiting — it printed the last line and returned to the handler when the pizza was ready.

then also accepts an optional second argument: a failure handler. In practice, most developers prefer a separate catch for failures, which reads better and also catches errors from earlier steps — that is covered below.

6. How a promise runs, step by step

The timing of promises confuses beginners more than anything else, so let us trace a small program line by line.

console.log("1. Script starts");

const promise = new Promise((resolve) => {
  console.log("2. Executor runs");
  resolve("Data ready");
});

promise.then((value) => console.log("4. Handler got:", value));

console.log("3. Script ends");

Output:

1. Script starts
2. Executor runs
3. Script ends
4. Handler got: Data ready

What happened, in order:

  1. The script starts and prints its first line.
  2. new Promise() executes the executor immediately — synchronously — so line 2 prints here, and resolve marks the promise fulfilled.
  3. then does not run the handler now. It places the handler in the microtask queue, a waiting area for promise callbacks.
  4. The engine finishes all synchronous code, so line 3 prints.
  5. Only now the event loop picks handlers off the microtask queue, and line 4 prints.

The rule to remember: promise handlers never jump ahead of the synchronous code that is already running. This is why you cannot simply assign a promise's "future value" to a variable and use it on the next line — the value does not exist yet. await, covered shortly, gives you a comfortable way to write code that reads as if it did.

7. Promise chaining

Real tasks rarely have one step. You log in, then fetch the profile, then fetch the orders. Promises chain naturally: each then returns a new promise, so steps line up one after another.

How values travel down a chain

Promise.resolve("A")
  .then((value) => value + "B")
  .then((value) => value + "C")
  .then((value) => console.log(value));   // ABC

Two rules drive every chain:

  • If a handler returns a plain value, the next then receives that value.
  • If a handler returns a promise, the chain waits for it to settle, and the next then receives its result.

The second rule is what lets an asynchronous step sit in the middle of a chain without any nesting.

A realistic two-step chain

function getUser(name) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ name: name, id: 7 }), 500);
  });
}

function getOrders(userId) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(["Shoes", "Backpack"]), 500);
  });
}

getUser("Asha")
  .then((user) => {
    console.log("User:", user.name);
    return getOrders(user.id);        // return the promise: the chain waits
  })
  .then((orders) => {
    console.log("Orders:", orders.join(", "));
  });

Output after about one second:

User: Asha
Orders: Shoes, Backpack

Each step starts only after the previous one finishes, and each handler receives exactly the value it needs. Compare this with nested callbacks, where the same logic would push every step one indentation level deeper.

8. Error handling with catch and finally

One catch at the end of the chain

catch attaches a handler that runs when any promise in the chain rejects. A rejection behaves like an exception: it skips forward past every then until it finds a catch.

function checkAge(age) {
  return new Promise((resolve, reject) => {
    if (age >= 18) {
      resolve("Access granted");
    } else {
      reject("Under 18: access denied");
    }
  });
}

checkAge(15)
  .then((message) => console.log(message))
  .catch((error) => console.log("Error:", error))
  .finally(() => console.log("Check finished"));

Output:

Error: Under 18: access denied
Check finished

One catch at the end covers every step above it — a major reason promises replaced callbacks, where every level needed its own error branch.

Recovering in the middle of a chain

A catch does not have to be the last link. If it returns a normal value, the chain continues as if nothing went wrong — useful for fallbacks.

Promise.resolve("start")
  .then(() => {
    throw new Error("main server down");
  })
  .catch((error) => {
    console.log("Recovered from:", error.message);
    return "cached data";             // recovery value
  })
  .then((value) => console.log("Got:", value));

Output:

Recovered from: main server down
Got: cached data

If the catch itself throws, the new error moves to the next catch. If no catch exists anywhere, you get an unhandled promise rejection: the browser logs it in the console, and the work you planned after that point silently never happens.

finally for cleanup

finally runs in both cases — success and failure — and receives no arguments. It exists for cleanup: hiding a loading spinner, closing a connection, marking a request as finished.

9. async functions and await

async/await is newer syntax built on top of promises. It does not replace promises — every await works on a promise underneath — but it lets you write asynchronous code that reads like ordinary step-by-step code.

The two keywords

  • The async keyword goes before a function. It allows await inside, and it makes the function always return a promise (even a plain return value gets wrapped in one).
  • The await keyword goes before a promise. It pauses that function until the promise settles, then the expression evaluates to the fulfilled value. If the promise rejects, await throws the reason as an exception.

A first example

function deliverAfter(delayMs, value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value), delayMs);
  });
}

async function main() {
  console.log("Waiting for the parcel...");

  const parcel = await deliverAfter(1000, "Parcel arrived");

  console.log(parcel);
  console.log("Done");
}

main();

Output (the middle line appears after one second):

Waiting for the parcel...
Parcel arrived
Done

Two details worth noting. First, await pauses only the async function containing it — the rest of the page keeps running normally. Second, awaiting a plain non-promise value is harmless; the value simply passes through, which makes await safe even when you are unsure whether a function returns a promise. Because an async function itself returns a promise, you can await another async function — this is how async code composes cleanly.

10. Handling errors in async functions

Since a rejected promise makes await throw, the natural tool is try/catch — the same mechanism used for synchronous errors. finally works here too.

function fetchProfile() {
  return Promise.reject("Server error");
}

async function showProfile() {
  try {
    const profile = await fetchProfile();
    console.log(profile);                 // skipped
  } catch (error) {
    console.log("Caught:", error);        // Caught: Server error
  } finally {
    console.log("Request finished");      // always runs
  }
}

showProfile();

Output:

Caught: Server error
Request finished

This closes the loop with the chain version: a try/catch around several await lines behaves like one catch at the end of a then chain. Any rejection inside the block jumps to catch, and the lines after the failing await are skipped.

11. Rewriting a chain: then versus async/await

Both styles run on the same engine and behave identically; the choice is about readability.

// Chain style
function loadOrders() {
  return getUser(7)
    .then((user) => getOrders(user.id))
    .then((orders) => console.log(orders))
    .catch((error) => console.log(error));
}

// async/await style
async function loadOrders() {
  try {
    const user = await getUser(7);
    const orders = await getOrders(user.id);
    console.log(orders);
  } catch (error) {
    console.log(error);
  }
}
Aspectthen chainasync/await
Readabilitysteps read top to bottom, but values travel through parametersreads like plain code; values sit in normal variables
Error handlingone catch at the endtry/catch, familiar from synchronous code
Intermediate valuesmust be passed through returnssimply assign to a const
Debuggingstack traces cross handler boundariesbreakpoints and step-through feel like sync code

Modern codebases lean towards async/await for anything with more than one or two steps, and keep short then chains for one-off transformations. React code in this course uses both, so you need to read each fluently.

12. Running promises in parallel

When several async tasks do not depend on each other, awaiting them one by one wastes time. If two requests each take one second, awaiting them sequentially costs two seconds, while starting both and waiting together costs one. JavaScript ships four combinator methods for this.

Promise.all

const profile = deliverAfter(800, "Profile loaded");
const posts = deliverAfter(1200, "Posts loaded");

Promise.all([profile, posts]).then((results) => {
  console.log(results);
});

Output after about 1.2 seconds:

["Profile loaded", "Posts loaded"]

The results array keeps the original order, no matter which promise finished first. If any input rejects, Promise.all rejects immediately with that first reason, and the successful results are not reported.

Promise.allSettled

When you want every outcome even if some fail, use allSettled:

const good = Promise.resolve("OK");
const bad = Promise.reject("Failed");

Promise.allSettled([good, bad]).then((results) => {
  console.log(results);
});

Output:

[
  { status: "fulfilled", value: "OK" },
  { status: "rejected", reason: "Failed" }
]

Promise.race and Promise.any

race settles as soon as the first promise settles, fulfilled or rejected — handy for timeouts. any settles with the first promise that fulfills, ignoring rejections along the way.

MethodWaits forBehaviour on rejection
Promise.allall inputs to fulfillrejects immediately with the first rejection
Promise.allSettledall inputs to settlenever rejects; reports each outcome
Promise.racethe first input to settlerejects if the first settled input rejected
Promise.anythe first input to fulfillrejects with an AggregateError only if all inputs reject

13. Common mistakes with promises and await

  • Forgetting await. Without it you hold a promise object, not the value: const user = getUser(7); console.log(user.name); prints undefined. Inside an async function, write const user = await getUser(7);.
  • Sequential awaits for independent work. Two await lines in a row run one after the other. When the tasks are independent, wrap them in Promise.all and destructure the results.
  • Using forEach with async callbacks. forEach does not wait for promises, so the loop finishes before the work does. Use a for...of loop with await, or Promise.all over an Array.map of promises.
  • Unhandled rejections. Every chain needs a catch, and every await belongs inside a try (or the rejection must be handled by the caller).
  • Wrapping promise-returning functions in new Promise manually. The executor pattern is only needed for old callback-style APIs such as setTimeout; functions that already return promises should be used directly.
  • Forgetting return inside a then. A handler without a return passes undefined to the next step, silently breaking the chain.

14. A realistic worked example: loading a dashboard

Put the pieces together. A dashboard needs a profile and a list of posts, shows a spinner while loading, prints the data on success, and shows a message on failure.

function fetchJSON(url) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (url.includes("bad")) {
        reject("Could not reach " + url);
      } else {
        resolve({ url: url, items: 3 });
      }
    }, 600);
  });
}

async function loadDashboard() {
  console.log("Spinner on");

  try {
    const [profile, posts] = await Promise.all([
      fetchJSON("https://api.example.com/profile"),
      fetchJSON("https://api.example.com/posts")
    ]);

    console.log("Profile items:", profile.items);
    console.log("Post items:", posts.items);
  } catch (error) {
    console.log("Dashboard failed:", error);
  } finally {
    console.log("Spinner off");
  }
}

loadDashboard();

Output:

Spinner on
Profile items: 3
Post items: 3
Spinner off

If the second URL were changed to include bad, that request would reject and the output would become:

Spinner on
Dashboard failed: Could not reach https://api.example.com/bad
Spinner off

Walk through what this example uses from the page: a promise-returning function (fetchJSON), parallel requests with Promise.all inside an async function, await combined with destructuring, a single try/catch covering both requests, and finally for the spinner. When you meet data fetching in React later in the course, this exact shape — start the request, await, catch, clean up — is the pattern you will apply.

15. Reusable async helpers: wait, timeout and retry

Real projects rarely write promise logic from scratch every time. Instead, developers wrap common needs into small helper functions once and reuse them everywhere. Three classics are a delay, a timeout guard and a retry loop.

A delay helper

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function countdown() {
  console.log("3");
  await wait(1000);
  console.log("2");
  await wait(1000);
  console.log("1");
  await wait(1000);
  console.log("Go!");
}

countdown();

wait turns the callback-based setTimeout into a promise-returning function. After that, any async function can pause with await wait(...) — no nesting, no callbacks. You will see this tiny helper reused in every example below.

A timeout guard with Promise.race

function timeout(ms) {
  return new Promise((_, reject) => {
    setTimeout(() => reject(new Error("Timed out after " + ms + " ms")), ms);
  });
}

async function withTimeout(promise, ms) {
  return Promise.race([promise, timeout(ms)]);
}

const slowJob = wait(5000).then(() => "Job finished");

withTimeout(slowJob, 2000)
  .then((result) => console.log(result))
  .catch((error) => console.log("Gave up:", error.message));

// Output: Gave up: Timed out after 2000 ms

Promise.race settles with whichever promise settles first. Here the timeout rejects at two seconds, long before the job finishes, so the caller gets a clean, predictable failure instead of an endless wait. The underscore in (_, reject) is a common convention for a parameter you do not use.

A retry loop for flaky operations

async function withRetry(task, attempts) {
  let lastError;
  for (let i = 1; i <= attempts; i++) {
    try {
      return await task();
    } catch (error) {
      lastError = error;
      console.log("Attempt " + i + " failed:", error.message);
      await wait(300 * i);   // wait a little longer each time
    }
  }
  throw lastError;
}

let calls = 0;
const flaky = () => {
  calls++;
  return calls < 3
    ? Promise.reject(new Error("server busy"))
    : Promise.resolve("Data loaded");
};

withRetry(flaky, 5)
  .then((result) => console.log(result))
  .catch(() => console.log("All attempts failed"));

Output:

Attempt 1 failed: server busy
Attempt 2 failed: server busy
Data loaded

The whole trick is that return await task() sits inside the try. A rejection is caught, logged, and answered with another attempt. If every attempt fails, the last error is rethrown to the caller, who handles it in one place.

16. Sequential and parallel loops

One of the most practical decisions you will make is whether a loop of async tasks should run one after another or all at once. The difference is user-visible seconds.

function fetchUser(id) {
  return wait(1000).then(() => "User " + id);
}

async function loadSequentially() {
  console.time("sequential");
  const users = [];
  for (const id of [1, 2, 3]) {
    users.push(await fetchUser(id));   // each wait blocks the next
  }
  console.timeEnd("sequential");       // roughly 3000 ms
  return users;
}

async function loadInParallel() {
  console.time("parallel");
  const users = await Promise.all([1, 2, 3].map(fetchUser));
  console.timeEnd("parallel");         // roughly 1000 ms
  return users;
}

In the sequential version, the second request does not even start until the first has finished, so the waits pile up. In the parallel version, map calls fetchUser for every id immediately, producing three running promises, and Promise.all waits for all of them together.

  • Use parallel loading when the tasks are independent — three separate user profiles, for example.
  • Use sequential loading when steps depend on each other, or when the server should not receive several requests at once.

17. A first look at fetch with async/await

The most common real-world use of async/await is talking to a server. The browser's fetch function returns a promise, so it slots straight into everything you have learned. The next module of this course covers the Fetch API in depth; here is the shape you will use.

async function loadUser(id) {
  const response = await fetch("https://api.example.com/users/" + id);

  if (!response.ok) {
    throw new Error("Request failed with status " + response.status);
  }

  const user = await response.json();
  return user;
}

loadUser(12)
  .then((user) => console.log(user))
  .catch((error) => console.log("Could not load user:", error.message));

Two details trip up almost every beginner here:

  • fetch rejects only when the network itself fails. A 404 or 500 response still resolves successfully, which is why you must check response.ok yourself and throw when it is false.
  • There are two await lines because two promises are involved: one for the response headers, and one — response.json() — for reading the body.

18. Common mistakes and the correct way

A try block that does not actually catch

// Wrong: the rejection escapes the try block
try {
  loadUser(12);              // missing await
} catch (error) {
  console.log("Never runs");
}

// Correct
try {
  const user = await loadUser(12);
} catch (error) {
  console.log("Caught:", error.message);
}

try/catch only catches what happens while it is waiting. Without await, the function returns a promise instantly and the later rejection happens far outside the try. The fix is nearly always just adding the missing await.

Rejecting with plain strings

// Weak: the caller receives a bare string with no context
reject("not found");

// Better: reject with an Error object
reject(new Error("User 12 not found"));

An Error object carries a stack trace pointing at where the problem happened, which makes debugging far easier. Strings and numbers as rejection reasons lose that information.

Top-level await in the wrong place

await is only valid inside an async function — with one exception: top-level await works in ES modules (<script type="module"> or files loaded with import), but not in a plain classic script. If you write await directly inside a normal <script> and get a syntax error, wrap the code in an async function and call it.

Out-of-order responses from rapid calls

If a user types three searches quickly, the requests may finish in a different order than they started, and an older, slower response can overwrite a newer one. The standard fix is to tag each request and ignore stale results:

let latest = 0;

async function search(term) {
  const id = ++latest;
  const results = await searchAPI(term);
  if (id !== latest) return;   // an older request finished late: ignore it
  render(results);
}

async callbacks inside forEach

// Wrong: forEach does not wait, ids finishes empty
const ids = [];
list.forEach(async (item) => {
  ids.push(await getId(item));
});

// Correct (sequential)
for (const item of list) {
  ids.push(await getId(item));
}

// Correct (parallel)
const ids = await Promise.all(list.map((item) => getId(item)));

forEach fires all the callbacks and moves on without waiting for any of them. Choose for...of when order matters, or map plus Promise.all when you want speed.

19. Best practices

  • Every chain ends with a catch. Attach a catch to every promise chain, and keep every await inside a try or hand the returned promise to a caller that handles it.
  • Name promise-returning functions after their action. loadUser, saveOrder and fetchReport tell the reader that waiting is involved.
  • Keep async functions short and single-purpose. A function that loads, transforms and renders data is three functions; splitting them makes each easy to test.
  • Prefer Promise.all for independent work. Only await in sequence when the next step genuinely needs the previous result.
  • Use finally for cleanup. Loading spinners and connection flags belong there, so they are switched off on both the success and failure paths.
  • Reject with Error objects and meaningful messages, never with bare strings, in application code.
  • Do not mix styles in one flow. Pick then chains or async/await for a given function; switching midway confuses readers.
  • Guard against stale results whenever the same operation can be triggered repeatedly, such as search-as-you-type.

20. Practical project: Quote of the Moment

This small browser project uses every core idea from the page: creating a promise, resolving and rejecting, async/await, try/catch, and a loading state. It works by opening the file directly in a browser.

Step 1: create the file

Make a folder called quote-viewer containing one file, index.html.

Step 2: write the complete page

<!DOCTYPE html>
<html>
<head>
  <title>Quote of the Moment</title>
</head>
<body>
  <button id="loadBtn">Load a quote</button>
  <p id="status"></p>
  <blockquote id="quote"></blockquote>

  <script>
    const quotes = [
      { text: "Practice makes progress", author: "Classroom proverb" },
      { text: "First, solve the problem. Then, write the code.", author: "John Johnson" },
      { text: "Make it work, make it right, make it fast.", author: "Kent Beck" }
    ];

    function getQuote() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          if (Math.random() < 0.2) {
            reject(new Error("Network hiccup"));
          } else {
            const index = Math.floor(Math.random() * quotes.length);
            resolve(quotes[index]);
          }
        }, 800);
      });
    }

    async function showQuote() {
      const statusEl = document.getElementById("status");
      const quoteEl = document.getElementById("quote");

      statusEl.textContent = "Loading...";
      quoteEl.textContent = "";

      try {
        const quote = await getQuote();
        quoteEl.textContent = '"' + quote.text + '" — ' + quote.author;
        statusEl.textContent = "";
      } catch (error) {
        statusEl.textContent = "Could not load: " + error.message;
      }
    }

    document.getElementById("loadBtn").addEventListener("click", showQuote);
  </script>
</body>
</html>

Step 3: understand each part

  1. The simulated API. getQuote returns a promise that settles after 800 milliseconds. Roughly one click in five rejects with an Error, so you can develop against both outcomes without a real server.
  2. The loading state. showQuote immediately writes "Loading..." so the user sees feedback while the promise is pending.
  3. The await. The function pauses at await getQuote(). The button and the rest of the page stay responsive, because only this function is paused.
  4. The error path. A rejection makes await throw, the catch shows the message, and no unhandled rejection ever reaches the console.
  5. The wiring. The button's click listener calls the async function; the promise it returns is fire-and-forget here, which is acceptable because all errors are handled inside.

Step 4: test both paths

Open the file, click the button several times, and confirm you sometimes see a quote and sometimes the error message. Then change Math.random() < 0.2 to true so every click fails, and confirm the error path works every time. Finally, replace getQuote with a real fetch call once you reach the Fetch API module — nothing else needs to change, because fetch also returns a promise.

21. Practice Exercises

  1. Write a wait(ms) helper and an async function launch() that prints "3", "2", "1", "Liftoff" with one second between each line.
  2. Convert this callback function into a promise-returning one: function double(n, callback) { setTimeout(() => callback(n * 2), 500); }
  3. Chain three steps — getUser, getOrders, getInvoice — where each returns a promise, and print the final invoice with a single catch at the end.
  4. Rewrite your chain from the previous exercise using async/await with try/catch/finally, where finally prints "Done".
  5. Load three independent "reports" (simulate each with wait and a value) in parallel, print the results array, and use console.time to prove the total time equals the slowest report, not the sum.
  6. Wrap a five-second task in a two-second timeout using Promise.race, and print which one won.
  7. Find and fix the bug: async function show() { try { fetchUser(7); } catch (e) { console.log(e); } } — explain why the catch never fires.

22. Interview Questions and Answers

What is a promise, and which states can it be in?

A promise is an object representing the eventual result of an asynchronous operation. It starts pending, then settles exactly once as either fulfilled (with a value) or rejected (with a reason). Once settled, its state and value never change.

How are promises better than callbacks?

Callbacks nest deeper with every step, producing hard-to-read "callback hell", and each level needs its own error handling. Promises chain flat with then, let one catch cover the whole chain, and are composable — helpers like Promise.all coordinate several operations, which callbacks cannot do cleanly.

What does the async keyword change about a function?

It does two things: the function is allowed to use await inside, and it always returns a promise — even if you write return 5, the caller receives a promise fulfilled with 5.

Does await block the whole page?

No. await pauses only the async function it appears in. The browser's event loop keeps running, so clicks, animations and other code continue normally while that function waits.

Predict the output of this snippet:

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");

The output is A, D, C, B. Synchronous code runs first (A and D). Promise handlers sit in the microtask queue, which is drained before timers, so C prints next. The setTimeout callback is a macrotask and prints last, even with a zero delay.

When do you choose Promise.all versus Promise.allSettled?

Use Promise.all when all results are required and one failure should abort the whole operation — it rejects immediately with the first rejection. Use Promise.allSettled when you want every outcome regardless of failures, such as loading several independent widgets; it never rejects and reports each result with a status field.

What happens if a then handler returns another promise?

The chain waits for that promise to settle, and the next then receives its settled value rather than the promise itself. This is what lets an asynchronous step sit in the middle of a chain without nesting.

How do you handle errors with async/await, and what is finally for?

A rejection turns await into a thrown exception, so you wrap the awaits in try/catch, exactly like synchronous code. finally runs on both paths and is used for cleanup — hiding a spinner, closing a connection — since it needs no access to the result or error.

What is an unhandled promise rejection and how do you avoid it?

It is a rejected promise that no catch or try/catch ever handles. The browser logs a warning in the console and any code that depended on the result silently never runs. You avoid it by ending every chain with a catch and ensuring every await is covered by error handling.

How do you run async tasks in a loop: sequentially or in parallel?

Inside a for...of loop, await runs tasks one after another — correct when each step needs the previous result. For independent tasks, build the promises first with map and pass the array to Promise.all, so they run concurrently and the total time is roughly the slowest task.

Can you use await inside forEach?

No. forEach does not wait for the promises its callbacks return; the loop finishes while the work is still pending. Use for...of with await for sequential execution, or map combined with Promise.all for parallel execution.

23. Quick Revision Checklist

  • A promise is pending, then settles once as fulfilled or rejected — never both, never twice.
  • The executor passed to new Promise runs immediately and synchronously; the first call to resolve or reject wins.
  • Handlers run after synchronous code finishes, via the microtask queue.
  • A then returning a plain value passes it on; returning a promise makes the chain wait.
  • A rejection skips ahead to the nearest catch; a mid-chain catch that returns a value recovers the chain.
  • finally runs on both outcomes and receives no arguments.
  • An async function always returns a promise; await unwraps a promise or throws its rejection reason.
  • Promise.all fails fast, allSettled reports everything, race takes the first settler, any takes the first success.
  • Sync code first, then microtasks (promises), then timers.
  • Classic traps: missing await, forEach with async, sequential awaits on independent work, rejecting with strings.

24. Official Documentation and Further Reading

No official specification pages were issued with this course's research notes for this topic, so the curated resources below are the recommended reading. They connect what you learned here to the React work ahead:

  • 10 React features that let you delete old code in 2026 — lists legacy muscle-memory patterns, such as the "mounted flag" once used around asynchronous loading, that modern React features replace. Read it once you start fetching data inside components.
  • React Hooks Best Practices — since data fetching in React happens inside hooks, the async discipline from this page (single responsibility, cleanup, error handling) carries over directly.
  • 50 React Interview Coding Challenges — a structured set of challenges framed as the path from beginner to advanced, and a way to judge whether a project is ready for your portfolio.
  • Frontend Interview Questions 2026: React, JS & CSS — covers JavaScript questions alongside React and CSS, including the traps hidden inside simple-looking questions — promise and async questions are exactly that category.

Conclusion

Promises and async/await are the grammar of everything asynchronous you will build: fetching data, waiting on timers, coordinating several requests, and failing gracefully when a server does not cooperate. The mental model is small — a promise is a receipt that settles once, await pauses one function without freezing the page, and every path needs an error plan. The patterns you practised here — helpers like wait, withTimeout and withRetry, parallel loading with Promise.all, and the loading–result–error shape of the Quote of the Moment project — are the same ones you will reach for inside React components, where they become the foundation for hooks that load and display real data.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp