SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
JS Promises
to callback hell and back
by Adam Winick
email: dev@adamwinick.com
github.com/sinelanguage/
soundcloud.com/sinelanguage
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
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
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 implementations

ES6’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.
Why do we need Promises in Javascript?

Why should we care?
• JS functions at their core are synchronous

They execute logic, return values, and throw exceptions
• Modern JS in 2015 ( Node, consuming API’s, data fetching ) is mostly asynchronous

You 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 value

Become rejected with an exception

Demonstrate what you mean using code :
We now have behaviour formally reserved for synchronous logic :



1. Flattened callbacks
2. Return values from asynchronous function
3. Throw and Catch exceptions



For 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?
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
Promise you will show me a promise (object)
asynchronous fn returning a promise instead of relying on a cb
but what if my cb based fn doesn’t return a promise and I can’t modify it
Let’s see that again with a core node function like fs.readFile()
callback hell example tbt
solved with promises example tbt

Weitere ähnliche Inhalte

Was ist angesagt?

Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptŁukasz Kużyński
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS PromisesAsa Kusuma
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS a_sharif
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript PromisesAsa Kusuma
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script PromiseAlok Guha
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptLeonardo Borges
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...andreaslubbe
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best PraticesChengHui Weng
 
Intro to React
Intro to ReactIntro to React
Intro to ReactTroy Miles
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Languagegiurca
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesomeAndrew Hull
 
REACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScriptREACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScriptDeepu S Nath
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit TestingMihail Gaberov
 
React Lifecycle and Reconciliation
React Lifecycle and ReconciliationReact Lifecycle and Reconciliation
React Lifecycle and ReconciliationZhihao Li
 

Was ist angesagt? (20)

Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
ReactJS
ReactJSReactJS
ReactJS
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
High Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScriptHigh Performance web apps in Om, React and ClojureScript
High Performance web apps in Om, React and ClojureScript
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
Beautiful code instead of callback hell using ES6 Generators, Koa, Bluebird (...
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
 
React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
REACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScriptREACT.JS : Rethinking UI Development Using JavaScript
REACT.JS : Rethinking UI Development Using JavaScript
 
Async JavaScript Unit Testing
Async JavaScript Unit TestingAsync JavaScript Unit Testing
Async JavaScript Unit Testing
 
React Lifecycle and Reconciliation
React Lifecycle and ReconciliationReact Lifecycle and Reconciliation
React Lifecycle and Reconciliation
 

Ähnlich wie Avoiding callback hell with promises

Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15Cheryl Yaeger
 
What is Promise in Angular Development?
What is Promise in Angular Development?What is Promise in Angular Development?
What is Promise in Angular Development?Albiorix Technology
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesHùng Nguyễn Huy
 
Promises in JavaScript with jQuery
Promises in JavaScript with jQueryPromises in JavaScript with jQuery
Promises in JavaScript with jQueryRyan Blunden
 
Gr Node Dev Promises Presentation
Gr Node Dev Promises PresentationGr Node Dev Promises Presentation
Gr Node Dev Promises Presentationjasonsich
 
Moving towards Reactive Programming
Moving towards Reactive ProgrammingMoving towards Reactive Programming
Moving towards Reactive ProgrammingDeepak Shevani
 
React gsg presentation with ryan jung & elias malik
React   gsg presentation with ryan jung & elias malikReact   gsg presentation with ryan jung & elias malik
React gsg presentation with ryan jung & elias malikLama K Banna
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and ReduxAli Sa'o
 
ReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOSReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOSAndrei Popa
 
Everything to Know About React Re-Rendering: A Comprehensive Guide
Everything to Know About React Re-Rendering: A Comprehensive GuideEverything to Know About React Re-Rendering: A Comprehensive Guide
Everything to Know About React Re-Rendering: A Comprehensive GuideBOSC Tech Labs
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
Gitter marionette deck
Gitter marionette deckGitter marionette deck
Gitter marionette deckMike Bartlett
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Devang Garach
 
[React Native Tutorial] Lecture 6: Component, Props, and Network
[React Native Tutorial] Lecture 6: Component, Props, and Network[React Native Tutorial] Lecture 6: Component, Props, and Network
[React Native Tutorial] Lecture 6: Component, Props, and NetworkKobkrit Viriyayudhakorn
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
React.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIReact.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIMarcin Grzywaczewski
 
Automatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swiftAutomatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swiftInnovationM
 

Ähnlich wie Avoiding callback hell with promises (20)

Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
 
What is Promise in Angular Development?
What is Promise in Angular Development?What is Promise in Angular Development?
What is Promise in Angular Development?
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Promises in JavaScript with jQuery
Promises in JavaScript with jQueryPromises in JavaScript with jQuery
Promises in JavaScript with jQuery
 
Gr Node Dev Promises Presentation
Gr Node Dev Promises PresentationGr Node Dev Promises Presentation
Gr Node Dev Promises Presentation
 
Angular Promise vs Observable
Angular Promise vs ObservableAngular Promise vs Observable
Angular Promise vs Observable
 
Moving towards Reactive Programming
Moving towards Reactive ProgrammingMoving towards Reactive Programming
Moving towards Reactive Programming
 
React gsg presentation with ryan jung & elias malik
React   gsg presentation with ryan jung & elias malikReact   gsg presentation with ryan jung & elias malik
React gsg presentation with ryan jung & elias malik
 
JOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and ReduxJOSA TechTalks - Better Web Apps with React and Redux
JOSA TechTalks - Better Web Apps with React and Redux
 
Better web apps with React and Redux
Better web apps with React and ReduxBetter web apps with React and Redux
Better web apps with React and Redux
 
ReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOSReactiveCocoa - Functional Reactive Programming concepts in iOS
ReactiveCocoa - Functional Reactive Programming concepts in iOS
 
Everything to Know About React Re-Rendering: A Comprehensive Guide
Everything to Know About React Re-Rendering: A Comprehensive GuideEverything to Know About React Re-Rendering: A Comprehensive Guide
Everything to Know About React Re-Rendering: A Comprehensive Guide
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Gitter marionette deck
Gitter marionette deckGitter marionette deck
Gitter marionette deck
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
[React Native Tutorial] Lecture 6: Component, Props, and Network
[React Native Tutorial] Lecture 6: Component, Props, and Network[React Native Tutorial] Lecture 6: Component, Props, and Network
[React Native Tutorial] Lecture 6: Component, Props, and Network
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
React.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UIReact.js - and how it changed our thinking about UI
React.js - and how it changed our thinking about UI
 
Automatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swiftAutomatic reference counting (arc) and memory management in swift
Automatic reference counting (arc) and memory management in swift
 

Mehr von TorontoNodeJS

Node.js API pitfalls
Node.js API pitfallsNode.js API pitfalls
Node.js API pitfallsTorontoNodeJS
 
Safely Build, Publish & Maintain ES2015, ES2016 Packages Today
Safely Build, Publish & Maintain ES2015, ES2016 Packages TodaySafely Build, Publish & Maintain ES2015, ES2016 Packages Today
Safely Build, Publish & Maintain ES2015, ES2016 Packages TodayTorontoNodeJS
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event LoopTorontoNodeJS
 
Building your own slack bot on the AWS stack
Building your own slack bot on the AWS stackBuilding your own slack bot on the AWS stack
Building your own slack bot on the AWS stackTorontoNodeJS
 

Mehr von TorontoNodeJS (7)

Node.js API pitfalls
Node.js API pitfallsNode.js API pitfalls
Node.js API pitfalls
 
Safely Build, Publish & Maintain ES2015, ES2016 Packages Today
Safely Build, Publish & Maintain ES2015, ES2016 Packages TodaySafely Build, Publish & Maintain ES2015, ES2016 Packages Today
Safely Build, Publish & Maintain ES2015, ES2016 Packages Today
 
nlp_compromise
nlp_compromisenlp_compromise
nlp_compromise
 
KoNote
KoNoteKoNote
KoNote
 
Understanding the Single Thread Event Loop
Understanding the Single Thread Event LoopUnderstanding the Single Thread Event Loop
Understanding the Single Thread Event Loop
 
Node as an API shim
Node as an API shimNode as an API shim
Node as an API shim
 
Building your own slack bot on the AWS stack
Building your own slack bot on the AWS stackBuilding your own slack bot on the AWS stack
Building your own slack bot on the AWS stack
 

Kürzlich hochgeladen

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 

Kürzlich hochgeladen (20)

08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 

Avoiding callback hell with promises

  • 1. JS Promises to callback hell and back by Adam Winick email: dev@adamwinick.com github.com/sinelanguage/ soundcloud.com/sinelanguage
  • 2. 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
  • 3. 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
  • 4. 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 implementations
 ES6’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.
  • 5. Why do we need Promises in Javascript?
 Why should we care? • JS functions at their core are synchronous
 They execute logic, return values, and throw exceptions • Modern JS in 2015 ( Node, consuming API’s, data fetching ) is mostly asynchronous
 You 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 value
 Become rejected with an exception

  • 6. Demonstrate what you mean using code :
  • 7. We now have behaviour formally reserved for synchronous logic :
 
 1. Flattened callbacks 2. Return values from asynchronous function 3. Throw and Catch exceptions
 
 For 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?
  • 8. 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
  • 9. Promise you will show me a promise (object)
  • 10. asynchronous fn returning a promise instead of relying on a cb
  • 11. but what if my cb based fn doesn’t return a promise and I can’t modify it
  • 12. Let’s see that again with a core node function like fs.readFile()
  • 14. solved with promises example tbt