Promises in 30 Seconds
A Promise represents a value that may be available now, later, or never. States: pending, fulfilled, rejected.
const fetchUser = () =>
fetch("/api/user").then((res) => {
if (!res.ok) throw new Error("Failed");
return res.json();
});
Async/Await
Syntactic sugar over Promises — same behavior, cleaner code.
async function loadUser() {
try {
const res = await fetch("/api/user");
if (!res.ok) throw new Error("Failed");
return await res.json();
} catch (error) {
console.error(error);
throw error;
}
}
Top Interview Questions
Q: What does Promise.all do if one rejects?
It immediately rejects with the first rejection. Use Promise.allSettled when you need all results.
Q: Implement a simple Promise
class MyPromise {
constructor(executor) {
this.state = "pending";
this.value = undefined;
this.handlers = [];
const resolve = (value) => {
if (this.state !== "pending") return;
this.state = "fulfilled";
this.value = value;
this.handlers.forEach((h) => h.onFulfilled(value));
};
executor(resolve);
}
then(onFulfilled) {
if (this.state === "fulfilled") onFulfilled(this.value);
else this.handlers.push({ onFulfilled });
}
}
Q: Sequential vs parallel async?
// Parallel — faster
const [a, b] = await Promise.all([fetchA(), fetchB()]);
// Sequential — when B depends on A
const a = await fetchA();
const b = await fetchB(a.id);