PROMISES

In Javascript (and Node)

goal

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!

what we are coding

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)

before we dive in

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.

first gen: events

They are not really used anymore (not for that purpose).

 

See XHR's API for a good example.

second gen: callbacks

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).

 

second gen: callbacks (...)

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!

third gen: promises

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.

third gen: promises (...)

Promises are ...

 

a) future data

b) chainable

c) composable

d) easy to read

e) easy for error handling

third gen: promises (...)

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.

 

 

how does it work

a) new()

b) reject() / fulfill()

c) then()

d) catch()

e) all()

f) race()

g) Promise.resolve(), etc.

how does it work (...)

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

 

bunch o' links

let's create some code

fourth gen: async/await

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

Any questions?

Thanks for listening!

 

Twitter: @sim_walsh

GH: @simonwalsh

Promises in Javascript (and Node)

By Simon Walsh

Promises in Javascript (and Node)

  • 948