JavaScript Promise Exercises
Practice exercises for working with promises and async/await.
Promises are one of those things that make sense when you read about them, then fall apart when you try to write them yourself. The fix is practice. These exercises start with creating a promise from scratch and work up to running requests in parallel and retrying failures.
A promise is an object that represents a value that isn't ready yet. It is either pending, fulfilled with a value or rejected with an error.
Each exercise has a prompt and some starter code. Try it yourself before looking at the solution. You can run all of them in the browser console or Node.
Exercise 1: Create a wait function
Write a wait(ms) function that returns a promise which resolves after ms
milliseconds.
wait(1000).then(() => console.log("One second later"))
Solution
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))wait(1000).then(() => console.log("One second later"))// console (after 1s): One second later
The Promise constructor gives you a resolve function. Passing it straight to
setTimeout resolves the promise once the timer is done. We'll reuse wait in
the exercises below.
Exercise 2: Promisify a callback function
Here's an old callback-style function. Wrap it in a function called
getUserAsync that returns a promise instead.
function getUser(id, callback) {setTimeout(() => {if (id <= 0) {callback(new Error("Invalid id"))} else {callback(null, { id, name: "John" })}}, 500)}
Solution
const getUserAsync = (id) =>new Promise((resolve, reject) => {getUser(id, (error, user) => {if (error) {reject(error)} else {resolve(user)}})})getUserAsync(1).then((user) => console.log(user))// console: { id: 1, name: "John" }getUserAsync(0).catch((error) => console.error(error.message))// console: Invalid id
Errors are passed to reject and results to resolve. In Node,
util.promisify does this for any function that follows the (error, result)
callback style.
Exercise 3: Chain promises
Using getUserAsync, get the user with id 1, then pass their name to
getPosts, then log how many posts they have. Use .then() chaining, no
async/await.
const getPosts = (name) =>wait(500).then(() => [`${name}'s first post`, `${name}'s second post`])
Solution
getUserAsync(1).then((user) => getPosts(user.name)).then((posts) => console.log(`${posts.length} posts`)).catch((error) => console.error(error.message))// console: 2 posts
Returning a promise from .then() makes the next .then() wait for it. A
single .catch() at the end handles an error from any step in the chain.
Exercise 4: Fetch in parallel with Promise.all
Fetch these three users at the same time and log all of their names once every request is done.
const urls = ["https://jsonplaceholder.typicode.com/users/1","https://jsonplaceholder.typicode.com/users/2","https://jsonplaceholder.typicode.com/users/3",]
Solution
const getUsers = async () => {const responses = await Promise.all(urls.map((url) => fetch(url)))const users = await Promise.all(responses.map((res) => res.json()))console.log(users.map((user) => user.name))}getUsers()// console: ["Leanne Graham", "Ervin Howell", "Clementine Bauch"]
All three requests start right away instead of one after another, and the
results come back in the same order as urls. If any one of them rejects,
Promise.all rejects too. For when you do need to go one at a time, see
Looping Through Async Methods in JavaScript.
Exercise 5: Add a timeout with Promise.race
Write a withTimeout(promise, ms) function. It should resolve with the
promise's value if it finishes in time, or reject with a "Timed out" error if
it takes longer than ms.
withTimeout(wait(500).then(() => "done"), 1000) // resolves with "done"withTimeout(wait(2000).then(() => "done"), 1000) // rejects with "Timed out"
Solution
const withTimeout = (promise, ms) => {const timeout = new Promise((_, reject) =>setTimeout(() => reject(new Error("Timed out")), ms))return Promise.race([promise, timeout])}withTimeout(wait(2000).then(() => "done"), 1000).then((value) => console.log(value)).catch((error) => console.error(error.message))// console: Timed out
Promise.race settles as soon as the first promise settles, whether it
resolves or rejects. Note the slow promise still keeps running in the
background. It's just ignored.
Exercise 6: Get every result with Promise.allSettled
Some of these tasks will fail. Log how many succeeded and the error message of each one that failed, without stopping at the first failure.
const tasks = [getUserAsync(1),getUserAsync(0),getUserAsync(2),getUserAsync(-1),]
Solution
const results = await Promise.allSettled(tasks)const fulfilled = results.filter((result) => result.status === "fulfilled")const rejected = results.filter((result) => result.status === "rejected")console.log(`${fulfilled.length} succeeded`)rejected.forEach((result) => console.error(result.reason.message))// console: 2 succeeded// console: Invalid id// console: Invalid id
Promise.allSettled never rejects. It waits for everything and gives you an
object for each promise with a status and either a value or a reason.
(Top-level await works in the console and in ES modules. Otherwise wrap this
in an async function.)
Exercise 7: Use the first success with Promise.any
You have the same file on two mirrors. Fetch from both and use whichever one succeeds first. If both fail, log a message.
const mirrors = ["https://mirror-one.example.com/data.json","https://mirror-two.example.com/data.json",]
Solution
const getFromMirrors = async () => {try {const res = await Promise.any(mirrors.map(async (url) => {const response = await fetch(url)if (!response.ok) {throw new Error(`${url} returned ${response.status}`)}return response}))return await res.json()} catch (error) {console.error("All mirrors failed", error.errors)}}
Unlike Promise.race, Promise.any ignores rejections until every promise has
rejected. Then it rejects with an AggregateError, which holds every error in
its errors array. Since fetch only rejects on network errors, we throw for a
bad status ourselves.
Exercise 8: Retry with async/await
Write a retry(fn, retries) function. It should call fn (a function that
returns a promise) and, if it rejects, try again up to retries times with a
short wait in between. If the last attempt fails, throw the error.
let attempts = 0const flakyRequest = async () => {attempts++if (attempts < 3) throw new Error(`Attempt ${attempts} failed`)return "Success"}
Solution
const retry = async (fn, retries = 3) => {for (let attempt = 1; attempt <= retries; attempt++) {try {return await fn()} catch (error) {if (attempt === retries) throw errorawait wait(attempt * 500)}}}retry(flakyRequest, 3).then((result) => console.log(result))// console: Success
The return await inside the try block matters. Without await, a rejected
promise would skip the catch and the retry would never happen. The wait grows
with each attempt so a struggling server gets a little breathing room. If you
want a refresher on handling these errors, see
How to use try...catch in JavaScript.
Once these feel comfortable, try combining them, like a Promise.all where each
request is wrapped in withTimeout and retry.
Have some feedback on this post? .