Errors and async · Lesson 36 of 45
Promises
A promise of a value to come: then, catch and Promise.all.
9 minutes2 games
A Promise represents a result that hasn't arrived yet (a data request, a file read). It has 3 states: pending, fulfilled (succeeded with a value) and rejected (failed with an error). Handle the value with .then() and failure with .catch().
pending ⏳
fulfilled ✓ → .then
or rejected ✗ → .catch
JavaScript
function wait(ms, value) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms))
}
function fail(ms) {
return new Promise((_, reject) => setTimeout(() => reject(new Error("Server is down")), ms))
}
wait(300, "data loaded")
.then((msg) => {
console.log(msg)
return msg.length
})
.then((n) => console.log("length:", n))
fail(400)
.then(() => console.log("never"))
.catch((err) => console.log("Caught:", err.message))
.finally(() => console.log("cleanup"))Several promises at once
JavaScript
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms))
Promise.all([wait(300, "user"), wait(200, "posts"), wait(100, "likes")])
.then((results) => console.log("all:", results))
Promise.race([wait(300, "slow"), wait(100, "fast")])
.then((winner) => console.log("race:", winner))Promise.all waits for all, running them in parallel (faster than one after another); race takes the first to finish.
What's the output?
Promise.resolve(2) .then((x) => x * 3) .then((x) => console.log(x))
What will this code print?
Quick question
You want data from 3 APIs at the same time and need all of it. What do you use?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.