LearnFrenzy
Sign in Take a free test
JS

JavaScript Programming · Topic 21 of 25

Async/Await Questions and Concepts

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Async/Await · Study material

async and await (ES2017) let you write promise-based code that reads like ordinary step-by-step code: const user = await getUser(id);. An async function always returns a promise, and await pauses that function – never the whole program – until a promise settles. Errors become exceptions you handle with try/catch. It is how almost all modern JavaScript talks to APIs, databases and files, and interviews probe the details: what an async function returns, where its synchronous part ends, why forEach ignores await, sequential vs parallel awaits, and return vs return await. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.

async functions return promises

Putting async before a function (declaration, expression, arrow or method) makes it return a promise: a returned value fulfils it, a thrown error rejects it. Callers use await or .then to get the result.

async function getNumber() {
  return 42;                         // wrapped: the function returns Promise<42>
}
async function fail() {
  throw new Error("nope");           // becomes a rejected promise
}
console.log(getNumber() instanceof Promise);
getNumber().then((v) => console.log("value:", v));
fail().catch((e) => console.log("rejected:", e.message));

Output

true
value: 42
rejected: nope

await pauses the function, not the program

await promise suspends the async function until the promise settles, then resumes it with the value (or throws the rejection reason). While it is suspended, the rest of the program – other code, timers, events – keeps running. await is allowed inside async functions and at the top level of ES modules.

const delay = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));

async function brew() {
  console.log("2. start brewing");
  const tea = await delay(10, "masala chai");   // brew() pauses here…
  console.log("4. ready:", tea);
  return tea;
}
console.log("1. order");
brew();
console.log("3. meanwhile, other code keeps running");   // …but the program does not

Output

1. order
2. start brewing
3. meanwhile, other code keeps running
4. ready: masala chai

The synchronous part

An async function runs synchronously, like a normal function, until it reaches its first await. The rest of it continues later as a microtask – even await null causes this pause.

// An async function runs synchronously until its first await
async function f() {
  console.log("B – inside f, before await");
  await null;
  console.log("D – resumed later, as a microtask");
}
console.log("A");
f();
console.log("C");

Output

A
B – inside f, before await
C
D – resumed later, as a microtask

Error handling with try / catch / finally

A rejected promise that is awaited throws at the await, so ordinary try/catch handles it, and finally runs on both paths. An error that is not caught rejects the async function's own promise – the caller must handle it, or it becomes an unhandled rejection.

const fetchUser = (id) => (id > 0 ? Promise.resolve({ id, name: "Asha" }) : Promise.reject(new Error("bad id")));

async function show(id) {
  try {
    const user = await fetchUser(id);       // a rejection is thrown here as an exception
    return `user ${user.name}`;
  } catch (e) {
    return `failed: ${e.message}`;
  } finally {
    console.log(`(request ${id} finished)`);
  }
}
console.log(await show(1));                 // top-level await: allowed in modules
console.log(await show(-1));

Output

(request 1 finished)
user Asha
(request -1 finished)
failed: bad id

Sequential vs parallel

Each await waits before the next line runs, so awaiting independent operations one by one is slow. Start them together and await Promise.all (or allSettled) instead; keep sequential awaits for steps that depend on the previous result.

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
let active = 0, maxActive = 0;
const task = async (name, ms) => {
  maxActive = Math.max(maxActive, ++active);
  await delay(ms);
  active--;
  return name;
};

const seq = [];
for (const [n, ms] of [["a", 20], ["b", 10]]) seq.push(await task(n, ms));   // one after another
console.log("sequential:", seq, "max at once:", maxActive);

maxActive = 0;
const par = await Promise.all([task("a", 20), task("b", 10)]);             // both start immediately
console.log("parallel:", par, "max at once:", maxActive);

Output

sequential: [ 'a', 'b' ] max at once: 1
parallel: [ 'a', 'b' ] max at once: 2

await in loops

for…of (and classic for/while) loops respect await: each iteration waits. forEach, map and friends do not – they call the async callback, receive a promise and move on. Use for…of for sequential work and await Promise.all(items.map(async …)) for parallel work.

const delay = (ms) => new Promise((r) => setTimeout(r, ms));
const log = [];

// forEach does NOT wait: it starts every async callback and moves on
[30, 10].forEach(async (ms) => { await delay(ms); log.push(`forEach ${ms}`); });

// for…of with await runs the steps one by one, in order
for (const ms of [30, 10]) { await delay(ms); log.push(`for…of ${ms}`); }

await delay(40);
console.log(log);

Output

[ 'forEach 10', 'forEach 30', 'for…of 30', 'for…of 10' ]

What await accepts

await works on any value: a promise is waited for, a thenable is adopted, and a plain value is returned unchanged (after a microtask). async works with every function form.

const value = await 5;                                   // a non-promise is simply returned (after a tick)
const fromThenable = await { then: (resolve) => resolve("thenable") };
const shop = { async greet() { return "hi"; } };         // async method
const double = async (n) => n * 2;                       // async arrow function
console.log(value, fromThenable, await shop.greet(), await double(21));

Output

5 thenable hi 42

Common mistakes

  • Forgetting await – you get a Promise object instead of the value.
  • await inside a non-async callback – SyntaxError; make the callback async.
  • Using forEach with async callbacks – nothing waits for them.
  • Awaiting independent calls one by one – slow; use Promise.all.
  • return promise inside try without await – the rejection escapes the catch.
  • No try/catch and no .catch – unhandled rejection.
  • Testing an async function's result in an if – a promise is always truthy.

Key points to remember

  • async functions always return a promise; throw → rejection.
  • await pauses only the current async function.
  • Code before the first await runs synchronously.
  • Use try/catch/finally around awaits.
  • Parallel: await Promise.all([...]); sequential: await each step.
  • for…of waits; forEach does not.
  • Top-level await works only in ES modules.

Frequently asked questions

Is async/await faster than promises?

It is the same mechanism with nicer syntax. Speed depends on whether independent work runs in parallel, not on the syntax.

Can I use await in a normal script?

Only inside async functions. Top-level await needs an ES module (type="module" in browsers, .mjs or "type": "module" in Node.js).

How do I cancel an awaited operation?

APIs like fetch accept an AbortSignal; abort it and the awaited promise rejects with an AbortError. Generic promises cannot be cancelled, but you can stop waiting with a timeout via Promise.race.

Where can I learn more?

Read async and await, Promises and The Fetch API in the JavaScript tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About JavaScript Programming

Why it matters

  • JavaScript runs every web page and, with Node.js, servers, tools and APIs – it is the most used language in the world
  • Front-end, full-stack and MERN roles test JavaScript first, and many campus coding rounds allow it
  • "Predict the output" questions on hoisting, closures, this, coercion and the event loop are interview favourites
  • Modern ES6+ – let/const, arrow functions, destructuring, promises and async/await – is what companies expect from freshers

Who it is for

  • College students (B.Tech, BCA, MCA, B.Sc CS) learning web development and preparing for semester exams and viva
  • Freshers preparing for campus placements, online assessments and front-end interviews
  • Developers moving to React, Angular, Vue or Node.js who need strong core JavaScript
  • Anyone revising ES6 and asynchronous JavaScript before an interview

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs on concepts and ES6 features
  • "Predict the output" puzzles – hoisting, coercion, closures, promises and timers
  • "Find the error" debugging: SyntaxError, ReferenceError, TypeError and silent logic bugs
  • Coding problems with solutions and real output, every one run on Node.js – run any study example in your browser

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture, Cognizant tests
  • Front-end developer interviews
  • MERN / full-stack interviews
  • Online coding assessments
  • University practicals

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, debugging, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links