avoiding callback hell with promises

14
JS Promises to callback hell and back by Adam Winick email: [email protected] github.com/sinelanguage/ soundcloud.com/sinelanguage

Upload: torontonodejs

Post on 11-Feb-2017

451 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Avoiding callback hell with promises

JS Promises to callback hell and back

by Adam Winick email: [email protected]

github.com/sinelanguage/ soundcloud.com/sinelanguage

Page 2: Avoiding callback hell with promises

Pleased to meet you• Electronic musician, passionate developer, devoted father

• Sr Web Developer at Real Matters

• Current project is a realtime web app using jHipster (Angular/SpringMVC/Node with a dash of D3) in production and currently supporting a migration to React

• UI Designer

• Front End Developer / JavaScript SPAs

• iOS

• NodeJS

Page 3: Avoiding callback hell with promises

Why another presentation on promises?

• This is the intro to promises I wish I had before reading all the currently available intro to promises

• Not enough focus on the core promise concept, a library (and a library specific API) is introduced before all the concepts are explained: except for this article: http://robotlolita.me/2015/11/15/how-do-promises-work.html

• Now that we have a Promise Spec, we can start writing promises lean and native without a library specific API

Page 4: Avoiding callback hell with promises

What are Promises?

• As a programming concept : A promise represents the eventual result of an asynchronous operation

• They are there to help manage complexity in the order of execution of our functions in our apps.

• As a ECMA Specification :We finally have a Promise Specification and several implementationsES6’s native promise have adopted the Promise/A+ Spec:https://promisesaplus.com/In these implementations, at their core they give developers use of a “promise” object or function with a then method whose behaviour conforms to the Promise Specification.

Page 5: Avoiding callback hell with promises

Why do we need Promises in Javascript?Why should we care?

• JS functions at their core are synchronousThey execute logic, return values, and throw exceptions

• Modern JS in 2015 ( Node, consuming API’s, data fetching ) is mostly asynchronousYou can’t return values if they aren’t ready. You can’t throw exceptions, if nobody’s there to catch them.So we use callback functions to manage the order of execution.In complex situations this can result in “callback hell”.

• How do JS promises save me from hell ?The point of promises is to give us back functional composition and error bubbling in the async world. They do this by saying that your functions should return a promise(an eventual result), which can do one of two things:Become fulfilled by a valueBecome rejected with an exception

Page 6: Avoiding callback hell with promises

Demonstrate what you mean using code :

Page 7: Avoiding callback hell with promises

We now have behaviour formally reserved for synchronous logic : 1. Flattened callbacks 2. Return values from asynchronous function 3. Throw and Catch exceptionsFor a Promise to make (2) and (3) work, the asynchronous function itself should return a Promise Object. This Promise object has two methods, then and catch. The methods will later be called depending on the state (fulflled || rejected) of the Promise Object. The next question is: How do we convert an asynchronous function to return a Promise Object?

Page 8: Avoiding callback hell with promises

Differences between callbacks and promises

1. Callbacks are functions, promises are objects

Callbacks are just blocks of code which can be run in response to events such as as timers going off or messages being received from the server. Any function can be a callback, and every callback is a function.

Promises are objects which store information about whether or not those events have happened yet, and if they have, what their outcome is.

2. Callbacks are passed as arguments, promises are returned

Callbacks are defined independently of the functions they are called from – they are passed in as arguments. These functions then store the callback, and call it when the event actually happens.

Promises are created inside of asynchronous functions (those which might not return a response until later), and then returned. When an event happens, the asynchronous function will update the promise to notify the outside world.

3. Callbacks handle success and failure, promises don’t handle anything

Callbacks are generally called with information on whether an operation succeeded or failed, and must be able to handle both scenarios.

Promises don’t handle anything by default, but success and failure handlers are attached later.

4. Callbacks can represent multiple events, promises represent at most one

Callbacks can be called multiple times by the functions they are passed to.

Promises can only represent one event – they are either successful once, or failed once

Page 9: Avoiding callback hell with promises

Promise you will show me a promise (object)

Page 10: Avoiding callback hell with promises

asynchronous fn returning a promise instead of relying on a cb

Page 11: Avoiding callback hell with promises

but what if my cb based fn doesn’t return a promise and I can’t modify it

Page 12: Avoiding callback hell with promises

Let’s see that again with a core node function like fs.readFile()

Page 13: Avoiding callback hell with promises

callback hell example tbt

Page 14: Avoiding callback hell with promises

solved with promises example tbt