J

JavaScript Handbook

Clean • Professional

Asynchronous JavaScript — Top Interview Questions & Answers

4 minute

Asynchronous JavaScript — Interview Questions & Answers

Ques: What is Asynchronous JavaScript?

Ans: Asynchronous JavaScript allows code to run without blocking the main thread. It enables non-blocking operations like network requests, file reading, or timers.

Example:

console.log("Start");
setTimeout(() => console.log("Async task done"), 1000);
console.log("End");

Output:

Start
End
Async task done

Ques: Why is Asynchronous Programming important in JavaScript?

Ans: Because JavaScript runs on a single thread, async operations prevent:

  • UI freezing
  • Performance lag
  • Blocking network calls

It allows multiple tasks to progress simultaneously.

Ques: What are common asynchronous patterns in JavaScript?

  1. Callbacks
  2. Promises
  3. Async/Await

Ques: What is a callback function?

Ans: A callback is a function passed as an argument to another function, executed after a task is complete.

function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded");
  }, 1000);
}

fetchData((result) => console.log(result));

Ques: What are callback advantages and disadvantages?

Advantages:

  • Simple for small async tasks
  • Easy to implement

Disadvantages:

  • Callback hell (nested callbacks)
  • Difficult to handle errors and readability issues

Example of callback hell:

getUser(() => {
  getPosts(() => {
    getComments(() => {
      console.log("Done");
    });
  });
});

Ques: What is a Promise in JavaScript?

Ans: A Promise represents a value that will be available in the future — either success (fulfilled) or failure (rejected).

Syntax:

const promise = new Promise((resolve, reject) => {
  let success = true;
  success ? resolve("Done!") : reject("Error!");
});

promise.then(console.log).catch(console.error);

Ques: What are the three states of a Promise?

StateDescription
PendingInitial state
FulfilledOperation completed successfully
RejectedOperation failed

Ques: How does .then(), .catch(), and .finally() work?

fetchData()
  .then(data => console.log(data))   // success
  .catch(err => console.error(err))  // error
  .finally(() => console.log("Done")) // always runs

Ques: How do Promises solve callback hell?

Ans: They allow chaining, making async flows linear and readable.

getUser()
  .then(getPosts)
  .then(getComments)
  .then(console.log)
  .catch(console.error);

Ques: Can you create a Promise-based function manually?

function asyncTask() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve("Success!"), 1000);
  });
}

asyncTask().then(console.log);

Ques: What is Promise.all()?

Ans: Runs multiple promises in parallel and resolves when all succeed — or rejects if any fail.

Promise.all([
  Promise.resolve("A"),
  Promise.resolve("B"),
  Promise.resolve("C")
]).then(console.log);

Ques: What is Promise.race()?

Ans: Returns the first settled promise (fulfilled or rejected).

Promise.race([
  fetchData1(),
  fetchData2()
]).then(console.log);

Ques: What is Promise.any()?

Ans: Resolves when any one promise is fulfilled. Rejects only if all promises fail.

Promise.any([
  Promise.reject("Error"),
  Promise.resolve("Success")
]).then(console.log);

Ques: What is Promise.allSettled()?

Ans: Waits for all promises to settle (fulfilled or rejected) and returns their results.

Promise.allSettled([
  Promise.resolve("OK"),
  Promise.reject("Failed")
]).then(console.log);

Output:

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

Ques: What is async/await in JavaScript?

Ans: Introduced in ES2017, it provides a synchronous-looking syntax for writing asynchronous code using Promises.

async function fetchData() {
  const response = await fetch("<https://api.example.com>");
  const data = await response.json();
  console.log(data);
}

Ques: Why use async/await over Promises?

  • Cleaner, sequential code
  • Easier debugging
  • Automatic Promise handling
  • Error handling via try...catch

Ques: How does error handling work in async/await?

async function getData() {
  try {
    const res = await fetch("<https://api.fake.com>");
    const data = await res.json();
  } catch (err) {
    console.error("Error:", err);
  }
}

Ques: Can async functions return values?

Ans: Yes, async functions always return a Promise.

async function demo() {
  return "Hello";
}
demo().then(console.log); // "Hello"

Ques: How can you run multiple async functions in parallel?

await Promise.all([task1(), task2(), task3()]);

Ques: What happens if you forget to use await?

Ans: The function continues executing without waiting, returning a pending Promise.

Ques: Can you mix Promises and async/await?

Ans: Yes, they work together seamlessly.

async function fetchAll() {
  const data = await Promise.all([getUser(), getPosts()]);
  console.log(data);
}

Ques: What is an example of async/await replacing Promise chains?

Before (Promise chain):

getUser()
  .then(getPosts)
  .then(getComments)
  .then(console.log);

After (Async/Await):

async function showData() {
  const user = await getUser();
  const posts = await getPosts(user);
  const comments = await getComments(posts);
  console.log(comments);
}

Ques: What are common mistakes with async/await?

  • Forgetting await
  • Using await inside loops (causes slowdowns)
  • Not wrapping async calls in try...catch
  • Mixing callbacks with async functions incorrectly

Ques: What is the difference between synchronous and asynchronous JavaScript?

FeatureSynchronousAsynchronous
ExecutionOne task at a timeMultiple tasks can overlap
BlockingBlocks the main threadNon-blocking
ExampleLoops, DOM updatesAPI calls, setTimeout

Ques: What is the Event Loop in relation to async JS?

Ans: The Event Loop manages the execution of callbacks, Promises, and async tasks, ensuring that async code runs after the main thread is free.

Article 0 of 0