Boss lesson · Unit 01
Three requests at once
Await together: the slowest, not the sum
What you practise
async/awaitas pausable functions, sequential awaits vsgather/Promise.all, total time is the slowest not the sum, forgettingawait, results keep input order
Try a question from this lesson
Pick one
The three loads wait 30, 20 and 10 ms. About how long does the whole program take?
import asyncio
async def load(ms):
await asyncio.sleep(ms / 1000)
return ms
async def main():
a = await load(30)
b = await load(20)
c = await load(10)
print(a, b, c)
asyncio.run(main())const sleep = (ms) =>
new Promise((r) => setTimeout(r, ms));
async function load(ms) {
await sleep(ms);
return ms;
}
async function main() {
const a = await load(30);
const b = await load(20);
const c = await load(10);
console.log(a, b, c);
}
main();const sleep = (ms: number) =>
new Promise((r) => setTimeout(r, ms));
async function load(ms: number) {
await sleep(ms);
return ms;
}
async function main() {
const a = await load(30);
const b = await load(20);
const c = await load(10);
console.log(a, b, c);
}
main();Hint
When does the second load start: at the beginning, or after the first one has finished?
Correct answer
About 60 ms
Why
Each await pauses here until that load is done, so the second load has not even started while the first one waits. The waits add up: 30 + 20 + 10.
JavaScript noteJavaScript has no built-in sleep. The two-line sleep wraps setTimeout in a promise, so that it can be awaited.
TypeScript noteload has no return annotation: TypeScript infers Promise<number>, because an async function always returns a promise of whatever it returns.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Pause here, carry on elsewhere
An async function can pause at an await and pick up again later with the result.
While it is paused, the thread goes back to the event loop, which runs whatever else is ready.
Calling an async function does not wait for it. It hands you a ticket for a future result: a promise in JavaScript, a coroutine in Python. await waits for the ticket.
10 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 2× type the answer
- 1× order the lines
- 2× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.