Asynchronous Programming
First, some synchronous code:
Code execution is
- top to bottom
- logical
- line after line
In synchronous code, the code execution is stopped until a value is reached
- until an array is sorted...
- until a function returns a value...
- until a file is successfully all read and loaded...
Not always a return value is immediately available though
- waiting for user input
- waiting for a server to respond
- waiting for a different process/thread
- waiting for the sake of waiting (performing an action in an interval)
Waiting in a synchronous way means the entire program is stopped (frozen)
- Console.Readline();
- console.prompt();
- console.confirm();
How can we avoid that?
- callbacks
- Tasks / Promises
- Observables
- Streams
- async / await
Callback pattern
- passing/setting a function (or a lambda)
- common in languages where a function is a first-class citizen
- AJAX, Promises, Observers
- single callback pattern is usually 1:1
- Not necessarily just for asynchrony! LINQ!
LINQ
Observer pattern
- one subject, more observers
- many dependants can subscribe to an event
- callback functions are added to a list
- in a key moment all callbacks are called
- subscribing doesn't mean the previous callback is replaced
Master/Slave pattern
- addEventListener(eventName, cb)
- requestAnimationFrame(cb)
- requestIdleCallback(cb)
In the browser
Callback hell
Promise/Task to the rescue
- An object that wraps a callback
- Callback can be added later
- Observer pattern
Async / await
- Syntactic sugar on top of Promises / Tasks
- eradicates .then(() => {})
- code looks synchronous
Paralellism!
Questions
Function
By Martin Malinda
Function
- 771