JavaScript 07 · JavaScript in general
Asynchronous JavaScript
setTimeout and the event loop, Promise, async/await, errors, Promise.all and fetch.
Loading lesson…
JavaScript 07 · JavaScript in general
setTimeout and the event loop, Promise, async/await, errors, Promise.all and fetch.
Loading lesson…
Picture a restaurant with a single waiter. If after every order they stood by the kitchen waiting for the cook to finish, the other guests wouldn't even get to order. So they do it the smart way: they take the order to the kitchen, leave the guest a ticket ("your food is coming") and go to serve the next table. When the cook rings the bell, they bring the food.
JavaScript in the browser is that waiter – it has only one thread (it can only do one thing at a time, like a single worker). If it waited for the server's answer (which can easily take a second), the whole page would freeze: you couldn't click, type or scroll. So slow things aren't waited for, they're ordered – and the ticket for a future result is called a Promise.
console.log('A')setTimeout(() => console.log('B – after 1 second'), 1000)console.log('C')// Prints: A, C, … and a second later B// setTimeout doesn't wait! It just "orders" a function call and the code carries on.const id = setTimeout(() => alert('Boom'), 5000) // setTimeout returns a number (id) of the planned callclearTimeout(id) // cancels the planned call with that idconst tick = setInterval(() => console.log('tick'), 1000) // every secondclearInterval(tick) // stops it
The waiter has rules: first they finish what they're doing right now (synchronous code). Then they check the urgent tickets (microtasks – fulfilled Promises). Only then do they take the next ordinary task from the queue (setTimeout, a click, a server response).
console.log('1')setTimeout(() => console.log('4'), 0) // even with zero, after everything elsePromise.resolve().then(() => console.log('3')) // Promise.resolve() = a Promise fulfilled at once; a microtask – before the timeoutconsole.log('2')// 1, 2, 3, 4
What you see: Code with console.log, setTimeout and a Promise. The button runs it and shows the order the output appeared in.
Try it:
queueMicrotask – a function that plans a microtask directly), and setTimeout with zero right at the end.The takeaway: setTimeout(fn, 0) doesn't mean "right now" but "when there's time". Synchronous code always finishes completely before anything asynchronous gets its turn.
Loading the interactive part…
A Promise is an object that stands in for a value that isn't available yet. It can be in one of three states:
| State | Meaning | The restaurant ticket |
|---|---|---|
pending | we're waiting | the food is cooking |
fulfilled | fulfilled – we have the value | the food is on the table |
rejected | rejected – an error happened | they ran out of ingredients |
The examples use fetchUser and fetchPosts. They're helper functions of the course that pretend to be a server: they return the data only after a while, so they return a Promise right away instead. Section 7 shows a real call to a server.
const promise = fetchUser(1) // returns a Promise right away, the data isn't there yetconsole.log(promise) // Promise { <pending> }// .then – "when it's ready, do this"promise.then((user) => console.log(user.name))// .catch – "if it goes wrong", .finally – "either way"fetchUser(99).then((user) => console.log(user.name)).catch((error) => console.error('It failed:', error.message))// console.error prints a red error to the console; error is the error object, error.message its text.finally(() => console.log('Done (success or error)'))
fetchUser(1).then((user) => fetchPosts(user.id)) // returns another Promise….then((posts) => posts.items.length) // …and the next then gets its result.then((count) => console.log(count)).catch((error) => console.error(error)) // one catch for errors from the whole chain
Usually you just receive Promises (from fetch, from libraries). But sometimes it's handy to make your own – typically for waiting:
// new Promise((resolve, reject) => …) – the Promise hands your function two functions:// call resolve(value) on success, reject(error) on failurefunction sleep(ms) {return new Promise((resolve) => {setTimeout(resolve, ms) // after ms it calls resolve → the Promise is fulfilled})}sleep(1000).then(() => console.log('A second has passed'))// A Promise that can failfunction rollDice() {return new Promise((resolve, reject) => {const n = Math.ceil(Math.random() * 6)if (n === 1) reject(new Error('You rolled a one')) // new Error(text) creates an error object with a textelse resolve(n)})}
.then chains work, but they're hard to read. async/await does the same thing and reads like ordinary code, top to bottom:
// With thenfunction showUserPosts(id) {return fetchUser(id).then((user) => fetchPosts(user.id)).then((posts) => console.log(posts.items))}// With async/await – the sameasync function showUserPosts(id) {const user = await fetchUser(id) // wait for the userconst posts = await fetchPosts(user.id) // then for the postsconsole.log(posts.items)}
await "unwraps" a Promise: it waits until it's fulfilled and returns its value. Only this function waits – the rest of the page keeps running.await can only be used inside a function marked async (or at the top level of a module – a file, see JavaScript 08).async function always returns a Promise. Even if you write return 5, the caller gets a Promise with a five.async function getNumber() {return 5}getNumber() // Promise { 5 } – not 5!const n = await getNumber() // 5getNumber().then((n) => …) // or like this// An async arrow functionconst loadUser = async (id) => {const user = await fetchUser(id)return user.name}
When something goes wrong, JavaScript throws an error: the function ends at once and the error "flies" outwards until something catches it. You can throw an error yourself with throw new Error('what happened'). You catch it with a try … catch block:
async function loadProfile(id) {try {const user = await fetchUser(id) // if this fails…return user} catch (error) {console.error(error.message) // …it jumps herereturn null} finally {console.log('Loading finished') // always runs (success or error)}}
When you need several independent things, there's no point waiting for each one separately. A waiter doesn't take orders to the kitchen one at a time, waiting for each to be cooked, either.
// ❌ One by one: 4 × ~1 s = ~4 sconst users = []for (const id of [1, 2, 3, 4]) {users.push(await fetchUser(id))}// ✅ All at once: ~1 s (as long as the slowest one takes)const users = await Promise.all([1, 2, 3, 4].map((id) => fetchUser(id)))// ↑ map starts all 4 loads right away, all waits for all of themconst [user, posts] = await Promise.all([fetchUser(1), fetchPosts(1)]) // different things at once
What you see: Two buttons that load four users from the fake API (each answers in 0.3–1.5 s). The bars show when each load started and finished.
Try it:
The takeaway: Start independent loads all at once with Promise.all. One by one only when the next step needs the result of the previous one.
Loading the interactive part…
| Method | Fulfilled when… | Rejected when… |
|---|---|---|
Promise.all | all of them are fulfilled (results in order) | any of them fails (right away) |
Promise.allSettled | all of them finish – successfully or not | never |
Promise.race | the first one finishes successfully | the first one finishes with an error |
Promise.any | any of them is fulfilled | all of them fail |
// allSettled – when you don't want one error to bring everything downconst results = await Promise.allSettled([fetchUser(1), fetchUser(99)])// [{ status: 'fulfilled', value: {…} }, { status: 'rejected', reason: Error }]const found = results.filter((r) => r.status === 'fulfilled').map((r) => r.value)// race – a time limitconst timeout = new Promise((_, reject) => setTimeout(() => reject(new Error('Timed out')), 3000))const user = await Promise.race([fetchUser(1), timeout])
In the course we use a fake API (src/course/fakeApi.en.ts) so everything works offline. In a real app you talk to the server with the built-in fetch function:
async function loadUsers() {const response = await fetch('https://api.example.com/users')if (!response.ok) { // ⚠️ fetch does NOT fail on 404 or 500!throw new Error(`The server returned ${response.status}`) // status = the response's status number: 200 OK, 404 not found…}const users = await response.json() // the response body → a JS object (also a Promise)// JSON = the text format server and browser send data in; .json() turns it into objectsreturn users}// Sending dataawait fetch('/api/posts', {method: 'POST', // POST = I'm sending data (without method it's GET = I want data)headers: { 'Content-Type': 'application/json' }, // headers = extra details about the request: "I'm sending JSON"body: JSON.stringify({ title: 'Hello' }), // body = the data being sent; object → text in the JSON format})
Sometimes, while you wait, you find out you no longer need the answer. The typical example is a search that searches while you type. When you type "milk", four requests go out: for "m", "mi", "mil" and "milk". You only care about the last one. The older ones cause two problems:
The fix is to cancel the old requests. In the restaurant: the guest changes their mind and the waiter runs to the kitchen so they don't cook the original order. In JavaScript that's what AbortController is for (to abort = to stop, to call off). It works like a remote control and a receiver:
new AbortController() creates the remote control. You keep it. It has a single button: controller.abort() = "call it off".controller.signal is its receiver. You hand it to the request: fetch listens to it and stops the moment you press abort().const controller = new AbortController() // 1. create the remote controlasync function search() {try {// 2. hand the receiver (signal) to fetch – in the second argument, just like method for POST above// ?q=react = a parameter in the address: the search text "react"const response = await fetch('/api/search?q=react', { signal: controller.signal })const results = await response.json()console.log(results)} catch (error) {if (error.name === 'AbortError') { // 4. we cancelled it ourselves → nothing went wrongconsole.log('Search cancelled')return}console.error('Search failed:', error.message) // a real error, e.g. the network is down}}search()setTimeout(() => controller.abort(), 200) // 3. after 200 ms press "call it off" (if the search is still running)
What happens after abort(): fetch stops waiting for the server and its Promise is rejected with an error. So await throws the error and the code jumps to catch – exactly as with an error from section 5. Besides message (the error's text), every error object has a name (the kind of error). A cancellation is called 'AbortError', so by the name you can tell "I called it off myself, nothing happened" from a real error you need to show the user.
A search while typing then looks like this – every new search first cancels the previous one:
// showResults and showError are made-up functions: they show the results / the error on the pagelet controller = null // the remote control of the search in progress (none yet)async function searchFor(text) {controller?.abort() // cancel the previous search; ?. = only if there is one (JavaScript 06)controller = new AbortController() // a new remote control – the old one is "used up" after abort()try {const response = await fetch(`/api/search?q=${text}`, { signal: controller.signal })showResults(await response.json())} catch (error) {if (error.name !== 'AbortError') showError(error.message) // a cancellation isn't an error, don't show it}}// the user types "mil" – every letter calls searchFor:searchFor('m') // starts searching for "m"searchFor('mi') // cancels "m", starts "mi"searchFor('mil') // cancels "mi", starts "mil" → only this search shows its results
What you see: A product search over the fake API, which answers after 0.3–1.5 s. Below the field is the list of requests sent, and below that the results currently shown.
Try it:
The takeaway: Cancelling the old request solves both problems at once: the browser doesn't wait for useless data and an old answer can no longer overwrite the new one.
Loading the interactive part…
In React you'll meet this again in lesson Hooks 01: there a request is cancelled in the effect's so-called cleanup function, which React calls when the search text changes or the component disappears from the page.
Most of the mistakes below share one root: you forget that an asynchronous function doesn't return a value but a ticket (a Promise), and that you have to wait for the ticket. The code usually doesn't crash – it just does something other than you expect. That's why it pays to know them in advance.
In the examples, ids is an array of numbers, e.g. [1, 2, 3], and save(id) is a made-up async function that saves something on the server and returns a Promise.
// ❌ Not like thisconst user = fetchUser(1) // fetchUser returns a Promise RIGHT AWAY, the data isn't there yetconsole.log(user) // Promise { <pending> }console.log(user.name) // undefined – a Promise has no name// ✅ Like thisconst user = await fetchUser(1) // wait until the Promise is fulfilled and take its valueconsole.log(user.name) // 'Anna Smith'
Without await the variable holds the ticket, not the food. JavaScript reports no error – a Promise is an ordinary object, and when you ask for a property it doesn't have, you get undefined (as with any object). How to spot it: when an asynchronous function gives you undefined, or text shows [object Promise], log the whole variable. You'll see Promise { <pending> } and know an await is missing.
// ❌ Not like thisfunction showUser() {const user = await fetchUser(1) // 💥 SyntaxError: await is only valid in async functions}// ✅ Like thisasync function showUser() {const user = await fetchUser(1)}
await only works inside a function marked async (section 4). Here at least JavaScript reports the error right away (SyntaxError = a mistake in how the code is written) and the whole file doesn't run. A common trap: await inside a nested function, such as an arrow function in setTimeout. The function that await stands directly in must be async – it's not enough that the function one level up is.
// ❌ Not like thisids.forEach(async (id) => {await save(id)})console.log('Done') // prints RIGHT AWAY – the saving is still running// ✅ One by one: for…of waits for each save before starting the nextfor (const id of ids) {await save(id)}console.log('Done') // once everything is saved// ✅ All at once: map starts every save, Promise.all waits for all of them (section 6)await Promise.all(ids.map((id) => save(id)))console.log('Done') // once everything is saved
Why it doesn't work: forEach (from lesson JavaScript 04) just calls your function for each item and moves on. Your function is async, so at its first await it returns a Promise – and forEach throws it away, it waits for nothing. So the await inside does wait, but only inside that small function, not the code after forEach. It's like a waiter who hands the orders to the kitchen and immediately announces "everyone has finished eating".
Which fix to pick: for…of when the order matters or the next step needs the previous result. Promise.all when the saves are independent – it's faster, because they run at the same time.
// ❌ Not like thisconst names = ids.map(async (id) => {const user = await fetchUser(id)return user.name})console.log(names) // [Promise, Promise, Promise] – no names// ✅ Like this: wrap it in Promise.all and wait for thatconst names = await Promise.all(ids.map(async (id) => {const user = await fetchUser(id)return user.name}),)console.log(names) // ['Anna Smith', 'Peter Brown', 'Eve Davis']
map puts into the new array whatever your function returns. And an async function always returns a Promise (section 4) – even if you write return user.name in it. That's why you get an array of tickets. Promise.all turns them into one ticket that is fulfilled with an array of all the values, and await unwraps it. The names are in the same order as ids, even if the answers arrive in a jumbled order.
// ❌ Not like thisasync function showUser(id) {const user = await fetchUser(id) // for id 99 it throws "User 99 doesn't exist"…console.log(user.name) // …this line never runs}showUser(99) // in the console: Uncaught (in promise) Error: User 99 doesn't exist// ✅ Like thisasync function showUser(id) {try {const user = await fetchUser(id)console.log(user.name)} catch (error) {console.error('It failed:', error.message) // here you can show the error to the user}}
An error from await ends the function immediately (section 5). If you don't catch it anywhere, it ends up only as a red message in the console – which the user doesn't see. Nothing happens on the page: "Loading…" spins forever, or nothing shows up at all. Every server call therefore needs a try … catch (or .catch) in the place where you know what to tell the user.
// ❌ Not like thisconst response = await fetch('/api/users/99') // the server answers 404 Not Foundconst user = await response.json() // the body of the error response, e.g. { error: 'Not found' }console.log(user.name) // undefined – and no error, catch never runs// ✅ Like thisconst response = await fetch('/api/users/99')if (!response.ok) throw new Error(`The server returned ${response.status}`) // turn the 404 into a real errorconst user = await response.json()
This is the trap from section 7: fetch fails only when the network is down. A "404" or "500" answer is a success for it, so your catch never runs and you carry on with the body of the error response as if it were the data. Only the throw after checking response.ok turns it into an error catch can catch.
Two short async functions: one waits a moment, the other loads a user from the fake API.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
Six functions over the fake API: waiting, loading one and several users at once, handling an error and a time limit. What exactly each one should return is in the comments in the code. The check under the editor takes a moment because the API answers with a delay.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
try/catch; finally always runs.Promise.all. await in forEach doesn't work.fetch doesn't fail on 404/500 – check response.ok. You can cancel it with AbortController: hand its signal to fetch, abort() cancels it and fetch fails with an AbortError.fetchUser, sleep)fetchUser, sleep – from the file src/course/fakeApi.en.ts. The course fake API: data and functions pretending to be a server (with a delay, sometimes even with an error). In a real app you would call fetch() here.export interface User {id: numbername: stringemail: stringcity: string}export async function fetchUser(id: number): Promise<User> {await sleep(randomDelay())const user = users.find((u) => u.id === id)if (!user) throw new Error(`User ${id} doesn't exist`)return user}export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))