JavaScript Promises and Async/Await Interview Questions (With Answers)
12 JavaScript promise and async/await interview questions with answers and code: promise states, chaining, error handling, Promise.all vs allSettled vs race vs any, sequential vs parallel awaits, retries and a Promise.all polyfill.
Fetching data, waiting for timers and handling user actions are all asynchronous, so interviewers always test how well you handle promises and async/await. Here are 12 questions, from basic definitions to coding tasks like writing Promise.all and a retry helper.
Promise fundamentals#
Q1. What is a promise, and what problem does it solve?#
Answer: A promise is an object representing a value that will be available later: the eventual success or failure of an async operation. Promises replaced deeply nested callbacks ("callback hell") with chainable, composable code and a single error path.
// Callback hell
getUser(id, (user) => {
getOrders(user.id, (orders) => {
getInvoice(orders[0].id, (invoice) => console.log(invoice));
});
});
// Promises
getUser(id)
.then((user) => getOrders(user.id))
.then((orders) => getInvoice(orders[0].id))
.then(console.log)
.catch(console.error);Q2. What are the states of a promise?#
| State | Meaning | How it happens |
|---|---|---|
| pending | Not finished yet | Initial state |
| fulfilled | Finished with a value | resolve(value) |
| rejected | Finished with a reason (error) | reject(err) or a thrown error |
Fulfilled and rejected are both settled. A promise settles only once; later calls to resolve or reject are ignored.
const p = new Promise((resolve, reject) => {
resolve("first");
resolve("second"); // ignored
reject(new Error()); // ignored
});
p.then(console.log); // "first"Q3. How do you convert a callback-based function into a promise?#
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Generic "promisify" for Node-style (err, result) callbacks
function promisify(fn) {
return (...args) =>
new Promise((resolve, reject) => {
fn(...args, (err, result) => (err ? reject(err) : resolve(result)));
});
}
const readFileAsync = promisify(require("fs").readFile);
await delay(500);Node also ships util.promisify and promise-based APIs like fs/promises.
Q4. How does promise chaining work?#
Answer: Every .then() returns a new promise. Whatever the handler returns becomes the next value; if it returns a promise, the chain waits for it. If a handler throws, the chain jumps to the nearest .catch().
Promise.resolve(2)
.then((n) => n * 3) // 6
.then((n) => delay(100).then(() => n + 1)) // waits, then 7
.then((n) => { throw new Error(`bad ${n}`); })
.then(() => console.log("skipped"))
.catch((e) => { console.log(e.message); return 0; }) // "bad 7"
.then((n) => console.log("recovered with", n)); // "recovered with 0"If you call an async function inside .then() without returning it, the chain doesn't wait and errors from it escape the .catch().
async/await and error handling#
Q5. What does async/await do under the hood?#
Answer: An async function always returns a promise. await pauses that function until the awaited promise settles, then resumes it (as a microtask) with the value, or throws the rejection reason. It is syntax sugar over promises that makes async code read top to bottom.
async function loadInvoice(id) {
try {
const user = await getUser(id);
const orders = await getOrders(user.id);
return await getInvoice(orders[0].id);
} catch (err) {
console.error("Failed:", err);
throw err; // let callers decide what to do
} finally {
hideSpinner();
}
}
loadInvoice(1).then(render); // still a promise to the callerQ6. What is the difference between sequential and parallel awaits?#
// Sequential: ~2 seconds (each await waits for the previous one)
const a = await fetchUser(); // 1s
const b = await fetchProducts(); // 1s
// Parallel: ~1 second (both requests start immediately)
const [user, products] = await Promise.all([fetchUser(), fetchProducts()]);Answer: Use sequential awaits only when the second call needs the first result. Independent requests should start together and be awaited with Promise.all.
for...of with await runs one item at a time. arr.forEach(async ...) does not wait at all. For parallel work use await Promise.all(arr.map(async (x) => ...)).
Q7. Compare Promise.all, allSettled, race and any.#
| Method | Resolves when | Rejects when | Use case |
|---|---|---|---|
Promise.all | All fulfil (array of values, in order) | Any one rejects (fail fast) | Load everything a page needs |
Promise.allSettled | All settle (array of {status, value/reason}) | Never | Batch jobs where partial failure is fine |
Promise.race | The first one settles, if it fulfilled | The first one settles, if it rejected | Timeouts |
Promise.any | The first one fulfils | All reject (AggregateError) | Fastest of several mirrors |
const results = await Promise.allSettled([api("/a"), api("/b")]);
results.forEach((r) =>
r.status === "fulfilled" ? console.log(r.value) : console.warn(r.reason)
);Q8. How do you add a timeout to a promise?#
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
await withTimeout(fetch("/api/report"), 5000);
// For fetch specifically, also cancel the request:
await fetch("/api/report", { signal: AbortSignal.timeout(5000) });Point out that Promise.race only stops waiting; the underlying work keeps running unless you cancel it (for example with AbortController). See Fetch API error handling and AbortController.
Q9. What happens to an unhandled rejection?#
Answer: If a rejected promise has no handler, browsers fire an unhandledrejection event and log an error; Node.js (v15+) crashes the process by default. Always end chains with .catch() or wrap awaits in try/catch, and add a global handler for logging.
window.addEventListener("unhandledrejection", (e) => {
reportToMonitoring(e.reason);
});
process.on("unhandledRejection", (reason) => { // Node.js
logger.error(reason);
});Coding questions#
Q10. Implement Promise.all.#
function promiseAll(iterable) {
return new Promise((resolve, reject) => {
const items = Array.from(iterable);
const results = new Array(items.length);
let done = 0;
if (items.length === 0) return resolve([]);
items.forEach((item, i) => {
Promise.resolve(item) // also handles plain values
.then((value) => {
results[i] = value; // keep original order
done += 1;
if (done === items.length) resolve(results);
})
.catch(reject); // first rejection wins
});
});
}
promiseAll([1, Promise.resolve(2), delay(50).then(() => 3)]).then(console.log); // [1, 2, 3]Key points: preserve order by index, count completions instead of using push, handle non-promise values and the empty array.
Q11. Write a retry helper with exponential backoff.#
async function retry(fn, { retries = 3, baseDelay = 300 } = {}) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
if (attempt >= retries) throw err;
const wait = baseDelay * 2 ** attempt + Math.random() * 100; // jitter
await new Promise((r) => setTimeout(r, wait));
}
}
}
const data = await retry(() => fetch("/api/flaky").then((r) => {
if (!r.ok) throw new Error(r.status);
return r.json();
}));Q12. Run async tasks with a concurrency limit.#
Interviewers often ask this as "upload 100 files but at most 3 at a time".
async function runWithLimit(tasks, limit) {
const results = new Array(tasks.length);
let next = 0;
async function worker() {
while (next < tasks.length) {
const i = next++; // claim the next task
results[i] = await tasks[i]();
}
}
await Promise.all(Array.from({ length: Math.min(limit, tasks.length) }, worker));
return results;
}
const tasks = files.map((f) => () => upload(f));
await runWithLimit(tasks, 3);Tasks are passed as functions so they don't start until a worker picks them up.
Quick revision#
| Question | Short answer |
|---|---|
Does .then return the same promise? | No, always a new one |
| Can a promise settle twice? | No |
| What does an async function return? | Always a promise |
| Fail-fast combinator? | Promise.all |
| Never-rejecting combinator? | Promise.allSettled |
Does forEach wait for async callbacks? | No |
To understand when promise callbacks run, continue with JavaScript event loop interview questions.
Key takeaways#
- A promise is pending, then settles once as fulfilled or rejected.
- Each
.then()returns a new promise; return values and thrown errors flow down the chain. asyncfunctions return promises, andawaitpauses only that function.- Start independent work together and await it with
Promise.all; choose allSettled, race or any for other needs. - Always handle rejections, and know how to write Promise.all, retry and a concurrency limiter by hand.