Promises & async
19 steps in 6 sets of JavaScript.
JavaScript is single-threaded and pretends otherwise convincingly. Promises first, properly, because async/await is sugar over them and the sugar leaks.
Then async iteration, scheduling with the microtask queue, and finally canceling and rate-limiting with AbortController. Nineteen steps, and it is the tour that explains why your console.log printed in that order.
Promises
- PromisesConstructing a promise and chaining its outcomes.
- What a promise isA pending value that settles once, and never changes after.
- ChainingEach then returns a new promise, so the value flows down the chain.
- Concurrent promisesRunning many async operations at once.
- The four combinatorsall, allSettled, race and any differ in what counts as finished.
async and await
- async and awaitWriting asynchronous code that reads sequentially.
- Errors in async functionsawait turns a rejection into a throw, so try/catch works again.
- Sequential or parallelTwo awaits in a row wait twice; starting both first does not.
- await in a loop, and other trapsforEach ignores async, and await inside a loop serializes everything.
Iterating asynchronously
- for awaitConsuming an async iterable, one awaited value at a time.
- The iterable protocolAnything with Symbol.iterator works in for-of and spread.
Scheduling
- Microtasks and macrotasksPromises jump the queue: every microtask runs before the next timer.
- withResolvers and timersThe newer helpers: a promise you settle from outside, and awaitable sleep.
- Sleep and timeoutA promise that resolves after a delay, plus the timeout that races against it.
Canceling & limiting
- AbortControllerOne signal cancels whatever is listening, including a timer.
- Limiting concurrencyA pool of workers pulling from a shared queue of tasks.
- Retry with backoffTry again, waiting longer each time, and give up eventually.
- Fetch with retryRetries a failed request with a growing delay, because networks fail for a moment and then do not.
Encore
- fetch-repos.jsFetch a user's repos concurrently and rank them by stars.