David Bruant: Asynchronous Patterns
David Bruant (@DavidBruant) was talking at Scotland.js about asynchronous patterns, these are my notes from his talk.
Why async?
Traditional code is blocking - we wait for a request (HTTP, database, &c) to complete before continuing. Each instruction is blocking and sequential. Ideally we would send all our requests as soon as possible and deal with them as they complete.
- L1/L2: cache 1-4ns
- Memory: 19 micro seconds
- Disk: 2ms
- Network: 100ms+
- Light speed: Bordeaux -> Edinburgh 8ms
This is the first reason Node.js is awsome - doesn't wait for blocking IO.
Events
When two entities are working together then one cannot wait for the other to finish before doing something else. Events are how they collaborate. OO model isn't appropriate for this with properties and methods. How do we use this to express "when X happens, do Y". Events are being re-invented everywhere: Java observer, SQL has triggers, Node.js has EventEmitter, &c.
Events should be considered as part of our APIs. Properties + Methods + Events.
Event loop
We have a stack, a heap and a queue. The queue is where asynchronous code lives. When an event in the queue is processed to completion then the next event is processed. It's a while event in queue: do event
type of thing. With web workers there are two sets that communicate with messages.
Promises
Objects can emit at most one event eventually, "success" or "error".
Streams
This is an object that will repeatedly emit data events.
Streams and promises
An HTTP request is a stream of data that finishes with a promise.