Lesson 7 of 18 · 0 of 1 exercises solved
Promises & Async/Await
You will learn how JavaScript waits for slow work such as network without freezing, using and /await. Almost every real app needs this.
JavaScript handles slow operations (network requests, file reads) asynchronously. Instead of blocking the entire thread waiting for a response, it registers a and continues running. Async/await makes this look like synchronous code.
// Promises
function fetchUser(id) {
return new Promise((resolve, reject) => {
// Simulate an API call
setTimeout(() => {
if (id > 0) {
resolve({ id, name: "Alice" });
} else {
reject(new Error("Invalid user ID"));
}
}, 100);
});
}
// .then() chaining
fetchUser(1)
.then(user => {
console.log(user.name); // Alice
return fetchUser(2); // chain another promise
})
.then(user => console.log(user))
.catch(err => console.error(err.message));
// async/await — cleaner syntax for the same thing
async function getUser() {
try {
const user = await fetchUser(1);
console.log(user.name); // Alice
} catch (err) {
console.error(err.message);
}
}
getUser();// fetch() — built-in for HTTP requests
async function getGitHubUser(username) {
const response = await fetch(`https://api.github.com/users/${username}`);
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
const data = await response.json();
return data;
}
async function main() {
try {
const user = await getGitHubUser("torvalds");
console.log(user.name); // Linus Torvalds
console.log(user.public_repos); // lots
} catch (err) {
console.error("Failed:", err.message);
}
}
main();
// Run multiple promises in parallel
async function fetchAll() {
const [user1, user2] = await Promise.all([
getGitHubUser("torvalds"),
getGitHubUser("gvanrossum"),
]);
console.log(user1.name, user2.name);
}Common question
Does await pause the whole program?
A promise stands for a result that will exist later. async functions return promises, and await inside them pauses the function until a promise settles, letting the thread run whatever else is ready. That is how one thread handles many slow operations: of them holds the thread while it waits.
Start independent operations before awaiting any of them, and combine them with Promise.all or allSettled. Wrap awaits in try/catch to handle rejections. Never expect a promise to become its value; await it. And keep the synchronous parts short, because a long computation does block, promise or not.
Source: JavaScript runs on a single thread with an . The language has no blocking waits, and await is defined in terms of that loop.
Common mix-ups
Each of these sounds reasonable. Think about why it is wrong, then open the explanation.
await waits, and while it's waiting nothing else can happen.
A promise is a value that arrives later, so once it resolves I can read the value straight from it.
Awaiting three fetches one after another is as fast as starting all three at once.
Practice
Write wait(ms) that returns a promise resolving after ms milliseconds, and an async fetchName(name, ms) that waits then returns the name. In main, start all three fetches at once with Promise.all so the whole thing takes about 300 ms, not 600, and store the names in results.
Promises in parallel
let results = []
function wait(ms) {
// return a Promise that resolves after ms
}
async function fetchName(name, ms) {
// wait, then return the name
}
async function main() {
const start = Date.now()
// run fetchName('A', 300), fetchName('B', 200), fetchName('C', 100) concurrently
console.log(results, Date.now() - start, 'ms')
}
await main()
Press Run to try your code, then Check answer to grade it.Check yourself
What happens when you await a value that is not a promise, such as await 5?
Tip: use the ← and → keys to move between lessons.