JavaScript, inside out · Chapter 39 of 51
Promises
By the end of this chapter you can make a promise, chain steps that wait for each other, recover from failures, and turn an old callback API into one that returns promises. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Going async
- 6 tasks
- JavaScript
- In the all labs plan
The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.
Why you need this
Ravi has signed up delivery riders and a payment gateway, and none of them answer straight away. Asking the rider app where an order is takes a second; a UPI charge takes two. The receipt printer still uses a 2015 library that wants a callback. "When I ask a question," Ravi says, "the screen must not freeze while it waits."
A function you know so far must return its answer straight away, and these answers do not exist yet. You could hand over a callback for when the answer arrives, but then the next step goes inside that callback, the step after inside another, and every level needs its own error check. Miss one, and a failure simply disappears.
What you build: 6 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
delay: a promise that resolves after a wait
Write delay(ms, value). Return a promise (a real Promise) that resolves with value after ms milliseconds, and not a moment before: delay(3000, 'chai ready') is still pending at 2999 ms and resolves with 'chai ready' at 3000.
When no value is given, it resolves with undefined.
- Task 2
checkStock: a promise for both answers
Write checkStock(stock, item). stock is an object of counts, such as { ginger: 4, milk: 0 }. Always return a promise: one that resolves with the count when more than 0 are left, and one that rejects with an Error whose message is the item followed by is out of stock, like 'milk is out of stock', when the count is 0 or the item is not in stock at all.
It must never throw: even for a missing item, the call returns a rejected promise.
- Task 3
billOrder: chain the order and the price into one bill
Write billOrder(api, id). api.getOrder(id) resolves to an order { id, item, qty }, and api.getPrice(item) resolves to the price of one. Return a promise that resolves to the bill line: the qty, x, the item, =, then ₹ and qty times price, like '3 x masala chai = ₹120'.
If either lookup rejects, the promise you return rejects with that same error.
- Task 4
trackDelivery: a fallback message and a spinner that always hides
Write trackDelivery(api, id, ui). Call ui.showSpinner() straight away, before anything is waited for. Then ask api.track(id), and return a promise that resolves to 'Order 12: on the way' (Order, the id, a colon and a space, then the status) when track resolves to 'on the way'.
When track rejects, the promise still resolves, to 'Order 15: tracking unavailable'. Either way, call ui.hideSpinner() once the answer is in, not before, and before your promise resolves.
- Task 5 · interview question
Interview: loyaltyPoints, fix the chain that loses the points
loyaltyPoints(api, phone) is broken now: it always resolves to NaN. Fix it so it finds the customer with api.findCustomer(phone), looks up their points with api.getPoints(customer.id), and resolves to double the points: 120 points give 240.
- Task 6
promisify: the callback printer as a promise
Write promisify(fn). fn is an old callback-style function: it takes its own arguments and then a callback, which it calls later as callback(error, value). Return a new function that takes the same arguments, calls fn with them plus a callback of yours last, and returns a promise.
The promise rejects with the error when there is one, and otherwise resolves with the value, even when the value is 0.
What you will learn
- A promise: a value for an answer that is not ready yet, which settles once, fulfilled or rejected.
- then chains: each step can return a value or another promise, and the chain waits.
- catch and finally: one place for failures, and cleanup either way.
- Wrapping callbacks: settle a promise from inside a callback.
More in Going async
Build "Promises" yourself
Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.