Errors and async · Lesson 37 of 45
async and await
Write async code that reads like normal code.
8 minutes3 games
async/await is an easier way to work with promises. An async function returns a promise; inside it, await pauses that function only until the promise settles and gives back its value. Errors are caught with ordinary try/catch.
JavaScript
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms))
async function loadDashboard() {
try {
console.log("Loading…")
const user = await wait(300, { name: "Mona" })
const courses = await wait(200, ["HTML", "JS"])
console.log(`${user.name} has ${courses.length} courses`)
} catch (err) {
console.log("Failed:", err.message)
}
}
loadDashboard()
console.log("This prints before the data arrives")One after another, or together?
JavaScript
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms))
async function slow() {
const t = Date.now()
const a = await wait(300, "A")
const b = await wait(300, "B")
console.log("one by one:", a, b, Date.now() - t >= 600 ? "~600ms" : "")
}
async function fast() {
const t = Date.now()
const [a, b] = await Promise.all([wait(300, "A"), wait(300, "B")])
console.log("together:", a, b, Date.now() - t < 500 ? "~300ms" : "")
}
slow()
fast()What's the output?
async function f() {
return 5
}
f().then((v) => console.log(v + 1))
console.log("first")What will this code print?
Complete the code
Complete the function so it waits for the data.
function load() { const data = getData() return data }
Exercise
Write async function main() that awaits wait(100, 21) and prints double it (42), then call it.
Expected output: 42
JavaScript
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms))
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.