TechnicalMedium JavaScript
What is the difference between Promises and async/await?
Asked for Frontend Developer, Full-Stack Developer, Mobile Developer
Why they ask this: Almost every app calls APIs; interviewers check you can write and handle async code correctly.
Answer
A Promise represents a value that will be available later (pending, then fulfilled or rejected). async/await is syntax on top of promises that makes async code read like synchronous code.
js
// Promise chain
fetch('/api/jobs')
.then((res) => res.json())
.then((jobs) => console.log(jobs))
.catch((err) => console.error(err));
// async/await
async function loadJobs() {
try {
const res = await fetch('/api/jobs');
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (err) {
console.error(err);
}
}Points worth mentioning:
- An
asyncfunction always returns a promise. - Use
try/catchfor errors withawait. - Run independent requests in parallel with
await Promise.all([...])instead of awaiting one after another.
Can you explain this in your own words?