In Javascript (and Node)
This L&L is an intro to promises.
Hopefully, you will find them less daunting and mysterious after this talk.
And ideally you would also see why you should be using them in your code!
We will be coding examples of algorithms and techniques around one use case:
a) take a number
b) make (async) operations to it
c) get a result (or catch an error)
Javascript, since day one (of 14), was created to be asynchronous.
Of course, you could not block the program and wait for the user to do something when needed.
Still used a lot in the JS world, as they are an integral part of it and will always be... I think.
For example, Node still has a lot of its API using callbacks (ex: fs.readdir, etc.).
A lot of the of the Web API's are still using callbacks as well (ex: GeoLocation).
The problem with callback is that they are...
a) hard to compose, chain and nest
b) hard to debug and handle errors
c) hard to test
They create something called... Callback HELL!
Promises are the new-ish way of managing asynchronous calls and data.
A promise represents the eventual result of an asynchronous operation. Instead of registering a callback in the call to an async function, the function returns a promise. The caller registers callbacks with the promise to receive either a promise’s eventual value from the async operation or the reason why the promise cannot be fulfilled.
Promises are ...
a) future data
b) chainable
c) composable
d) easy to read
e) easy for error handling
Promise is now an official standard and lot of libraries now use them.
All the new Web async features will be using promises (ex: ServiceWorkers).
It's easy to convert a synchronous / callback-powered method into a thenable method.
a) new()
b) reject() / fulfill()
c) then()
d) catch()
e) all()
f) race()
g) Promise.resolve(), etc.
then() and catch() can pass along any type of values (async or not) in the then chain.
In a then, you can do 3 things:
1. return another promise,
2. return a synchronous value (or undefined)
3. throw a synchronous error
Using generators to pause a function until its async state is fulfilled.
See this link for further info: https://ponyfoo.com/articles/understanding-javascript-async-await
Thanks for listening!
Twitter: @sim_walsh
GH: @simonwalsh