SlideShare a Scribd company logo
Promises,
Promises, and
then Observables
A quick introduction into promises and
observables by Stefan Charsley
So many broken
promises
Just like every single new years resolution
What are Promises?
● Promises are a proxy object that represent the eventual completion or failure of an
asynchronous operation and its result.
● Promises have three states:
○ pending - the operation has not yet completed or failed (initial state)
○ fulfilled - the operation has completed
○ rejected - the operation failed
● Each Promise can only be “settled” (fulfilled or rejected) once
How are Promises created?
Promises can be created by our code or by 3rd party code for us to consume.
To create Promises we can use the constructor which takes a function as a parameter.
The function we pass will be called with two parameters, resolve and reject.
resolve and reject are both functions, and when called they set the state of the Promise to either
fulfilled or rejected respectively.
const myPromise = new Promise((resolve, reject) => {
// Our super complex asynchronous call that
// requires a new supercomputer
setTimeout(() => resolve('im done haha'), 0);
});
How are Promises used?
Promises are used by attaching handler functions using the then, catch, and finally functions
available on the Promise object instance. These handlers are executed in the order they are
attached.
const myFulfilledPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve('im done haha'), 0);
});
// Will print out: im done haha
myFulfilledPromise.then((value) => console.log(value));
const myRejectedPromise = new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('oh noes')), 0);
});
// Will print out: oh noes
myRejectedPromise.catch((error) => console.log(error.message));
Example
// Using fetch api which returns a promise
const myFetchPromise = fetch('http://example.com/movies.json');
const myDataPromise = myFetchPromise.then((response) => response.json());
myDataPromise.then((data) => console.log(data));
myDataPromise.catch((error) => console.log(error));
// You can also chain .then(), .catch(), and .finally()
// to attach multiple handlers at the same time
const myFetchPromise = fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
Bonus example (async/await)
// Marking functions as async, you can use the await keyword
// and take advantage of try catch
async function doSomeWork() {
try {
const response = await fetch('http://example.com/movies.json');
const data = await response.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
Questions?
None? Okay! Let’s move on!
Observe my terrible
code
It works on my machine
ReactiveX?
The ReactiveX learning curve:
Source:
https://twitter.com/hoss/status/742643506536153088
So what is ReactiveX programming?
● Everything is a stream of data/events
● Made up of observables and observers
● Combines the advantages of iterators with the flexibility of event-based asynchronous
programming
● Similar but different to functional reactive programming
○ Functional reactive programming operates on values that change continuously over time, while
ReactiveX operates on discrete values that are emitted over time.
What is an Observable?
An observable represents a stream of data that can arrive over time.
They can be created from anything but most often from DOM events and HTTP requests.
Observables don’t do anything and don’t activate a producer (like adding an event handler) until
there is a Subscription.
// import the fromEvent operator
import { fromEvent } from 'rxjs';
// grab button reference
const button = document.getElementById('myButton');
// create an observable of button clicks
const myObservable = fromEvent(button, 'click');
Subscriptions? Like Netflix? Not quite.
Subscriptions can be thought of as similar to Promise handlers, except that Subscribing to an
Observable actually activates the Observable.
Think of subscriptions like turning on the water tap, when you need the water you turn
(subscribe) the tap and the water begins to flow.
// import the fromEvent operator
import { fromEvent } from 'rxjs';
// grab button reference
const button = document.getElementById('myButton');
// create an observable of button clicks
const myObservable = fromEvent(button, 'click');
// for now, let's just log the event on each click
const subscription = myObservable.subscribe(event => console.log(event));
How’s that better than Promises?
Operators!
Operators are a way of modifying incoming values from a source observable, and returning a
destination observable of the transformed values. They can be used with the pipe function
which takes a an unlimited number of operators which will be performed in sequence as a chain.
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
// 'of' allows you to deliver values in a sequence
const dataSource = of(1, 2, 3, 4, 5);
// subscribe to our source observable
const subscription = dataSource
.pipe(
map(value => value + 1), // add 1 to each emitted value
filter(value => value % 2 === 0) // only accept multiples of 2
)
.subscribe(value => console.log(value)); // log: 2, 4, 6
Example
// import the fromEvent operator
import { fromEvent } from 'rxjs';
import { debounceTime, mergeMap } from 'rxjs/operators
import { http, HttpRequest } from 'observable-http-lib';
// grab textarea reference
const myTextarea = document.getElementById('myTextarea');
// create an observable of textarea inputs
const eventSource = fromEvent(myTextarea, 'input');
// only send http request once user has stopped typing for 500ms
const subscription = eventSource
.pipe(
debounceTime(500),
mergeMap((event) =>
http.request(new HttpRequest('POST', '/my_endpoint', { data: event.data }))
)
)
.subscribe((res) => console.log(`success: ${res}`), (err) => console.log(`fail: ${err}`));
Questions?
Why no questions? :(
Shameless plug: spread the word about MyMahi (mymahi.co.nz), it’ll keep me employed, please. PLEASE. PLEASE!!!!
FIN

More Related Content

PPTX
JavaScript Promises
L&T Technology Services Limited
 
PDF
Introduction to RxJS
Brainhub
 
PPTX
Rxjs ppt
Christoffer Noring
 
PPTX
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
PPTX
Java script errors & exceptions handling
AbhishekMondal42
 
PPTX
Express JS
Alok Guha
 
PDF
Javascript essentials
Bedis ElAchèche
 
PPTX
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
JavaScript Promises
L&T Technology Services Limited
 
Introduction to RxJS
Brainhub
 
Sharing Data Between Angular Components
Squash Apps Pvt Ltd
 
Java script errors & exceptions handling
AbhishekMondal42
 
Express JS
Alok Guha
 
Javascript essentials
Bedis ElAchèche
 
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 

What's hot (20)

PPTX
Angular 2.0 forms
Eyal Vardi
 
PPTX
ASP.NET Web API
habib_786
 
PDF
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PPT
Javascript
Manav Prasad
 
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PPTX
Angular Data Binding
Jennifer Estrada
 
PPTX
Angular Data Binding
Duy Khanh
 
PPTX
React hooks
Ramy ElBasyouni
 
PDF
Introduction To Angular's reactive forms
Nir Kaufman
 
PPTX
File system node js
monikadeshmane
 
PPT
PHP variables
Siddique Ibrahim
 
PPT
Oops concepts in php
CPD INDIA
 
PDF
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
PPT
JavaScript Tutorial
Bui Kiet
 
PDF
Introducing Async/Await
Valeri Karpov
 
PPTX
Angular tutorial
Rohit Gupta
 
PPTX
Javascript event handler
Jesus Obenita Jr.
 
PPTX
Ajax and Jquery
People Strategists
 
Angular 2.0 forms
Eyal Vardi
 
ASP.NET Web API
habib_786
 
JavaScript - Chapter 3 - Introduction
WebStackAcademy
 
Intro to Asynchronous Javascript
Garrett Welson
 
Javascript
Manav Prasad
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
Angular Data Binding
Jennifer Estrada
 
Angular Data Binding
Duy Khanh
 
React hooks
Ramy ElBasyouni
 
Introduction To Angular's reactive forms
Nir Kaufman
 
File system node js
monikadeshmane
 
PHP variables
Siddique Ibrahim
 
Oops concepts in php
CPD INDIA
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Edureka!
 
JavaScript Tutorial
Bui Kiet
 
Introducing Async/Await
Valeri Karpov
 
Angular tutorial
Rohit Gupta
 
Javascript event handler
Jesus Obenita Jr.
 
Ajax and Jquery
People Strategists
 
Ad

Similar to Promises, promises, and then observables (20)

PDF
Declarative presentations UIKonf
Nataliya Patsovska
 
PPTX
The Promised Land (in Angular)
Domenic Denicola
 
PDF
Advanced JavaScript - Internship Presentation - Week6
Devang Garach
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
PPT
You promise?
IT Weekend
 
PPTX
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
PDF
New improvements for web developers - frontend.fi, Helsinki
Robert Nyman
 
ODP
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
ODP
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
PDF
Using Akka Futures
Knoldus Inc.
 
PDF
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
PPT
My programming final proj. (1)
aeden_brines
 
PDF
Day 5
Vivek Bhusal
 
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
DOCX
Rhino Mocks
Anand Kumar Rajana
 
PPTX
How to perform debounce in react
BOSC Tech Labs
 
PDF
JavaScript Promises
Tomasz Bak
 
PPTX
Concurrent Rendering Adventures in React 18
Maurice De Beijer [MVP]
 
PDF
JavaScript Lessons 2023
Laurence Svekis ✔
 
PDF
Advanced redux
Boris Dinkevich
 
Declarative presentations UIKonf
Nataliya Patsovska
 
The Promised Land (in Angular)
Domenic Denicola
 
Advanced JavaScript - Internship Presentation - Week6
Devang Garach
 
Understanding Asynchronous JavaScript
jnewmanux
 
You promise?
IT Weekend
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 
New improvements for web developers - frontend.fi, Helsinki
Robert Nyman
 
Building serverless application on the Apache Openwhisk platform
Lucio Grenzi
 
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Codemotion
 
Using Akka Futures
Knoldus Inc.
 
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
My programming final proj. (1)
aeden_brines
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Codemotion
 
Rhino Mocks
Anand Kumar Rajana
 
How to perform debounce in react
BOSC Tech Labs
 
JavaScript Promises
Tomasz Bak
 
Concurrent Rendering Adventures in React 18
Maurice De Beijer [MVP]
 
JavaScript Lessons 2023
Laurence Svekis ✔
 
Advanced redux
Boris Dinkevich
 
Ad

Recently uploaded (20)

PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Presentation about variables and constant.pptx
kr2589474
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 

Promises, promises, and then observables

  • 1. Promises, Promises, and then Observables A quick introduction into promises and observables by Stefan Charsley
  • 2. So many broken promises Just like every single new years resolution
  • 3. What are Promises? ● Promises are a proxy object that represent the eventual completion or failure of an asynchronous operation and its result. ● Promises have three states: ○ pending - the operation has not yet completed or failed (initial state) ○ fulfilled - the operation has completed ○ rejected - the operation failed ● Each Promise can only be “settled” (fulfilled or rejected) once
  • 4. How are Promises created? Promises can be created by our code or by 3rd party code for us to consume. To create Promises we can use the constructor which takes a function as a parameter. The function we pass will be called with two parameters, resolve and reject. resolve and reject are both functions, and when called they set the state of the Promise to either fulfilled or rejected respectively. const myPromise = new Promise((resolve, reject) => { // Our super complex asynchronous call that // requires a new supercomputer setTimeout(() => resolve('im done haha'), 0); });
  • 5. How are Promises used? Promises are used by attaching handler functions using the then, catch, and finally functions available on the Promise object instance. These handlers are executed in the order they are attached. const myFulfilledPromise = new Promise((resolve, reject) => { setTimeout(() => resolve('im done haha'), 0); }); // Will print out: im done haha myFulfilledPromise.then((value) => console.log(value)); const myRejectedPromise = new Promise((resolve, reject) => { setTimeout(() => reject(new Error('oh noes')), 0); }); // Will print out: oh noes myRejectedPromise.catch((error) => console.log(error.message));
  • 6. Example // Using fetch api which returns a promise const myFetchPromise = fetch('http://example.com/movies.json'); const myDataPromise = myFetchPromise.then((response) => response.json()); myDataPromise.then((data) => console.log(data)); myDataPromise.catch((error) => console.log(error)); // You can also chain .then(), .catch(), and .finally() // to attach multiple handlers at the same time const myFetchPromise = fetch('http://example.com/movies.json') .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.log(error));
  • 7. Bonus example (async/await) // Marking functions as async, you can use the await keyword // and take advantage of try catch async function doSomeWork() { try { const response = await fetch('http://example.com/movies.json'); const data = await response.json(); console.log(data); } catch (error) { console.log(error); } }
  • 9. Observe my terrible code It works on my machine
  • 10. ReactiveX? The ReactiveX learning curve: Source: https://twitter.com/hoss/status/742643506536153088
  • 11. So what is ReactiveX programming? ● Everything is a stream of data/events ● Made up of observables and observers ● Combines the advantages of iterators with the flexibility of event-based asynchronous programming ● Similar but different to functional reactive programming ○ Functional reactive programming operates on values that change continuously over time, while ReactiveX operates on discrete values that are emitted over time.
  • 12. What is an Observable? An observable represents a stream of data that can arrive over time. They can be created from anything but most often from DOM events and HTTP requests. Observables don’t do anything and don’t activate a producer (like adding an event handler) until there is a Subscription. // import the fromEvent operator import { fromEvent } from 'rxjs'; // grab button reference const button = document.getElementById('myButton'); // create an observable of button clicks const myObservable = fromEvent(button, 'click');
  • 13. Subscriptions? Like Netflix? Not quite. Subscriptions can be thought of as similar to Promise handlers, except that Subscribing to an Observable actually activates the Observable. Think of subscriptions like turning on the water tap, when you need the water you turn (subscribe) the tap and the water begins to flow. // import the fromEvent operator import { fromEvent } from 'rxjs'; // grab button reference const button = document.getElementById('myButton'); // create an observable of button clicks const myObservable = fromEvent(button, 'click'); // for now, let's just log the event on each click const subscription = myObservable.subscribe(event => console.log(event));
  • 14. How’s that better than Promises? Operators! Operators are a way of modifying incoming values from a source observable, and returning a destination observable of the transformed values. They can be used with the pipe function which takes a an unlimited number of operators which will be performed in sequence as a chain. import { of } from 'rxjs'; import { map } from 'rxjs/operators'; // 'of' allows you to deliver values in a sequence const dataSource = of(1, 2, 3, 4, 5); // subscribe to our source observable const subscription = dataSource .pipe( map(value => value + 1), // add 1 to each emitted value filter(value => value % 2 === 0) // only accept multiples of 2 ) .subscribe(value => console.log(value)); // log: 2, 4, 6
  • 15. Example // import the fromEvent operator import { fromEvent } from 'rxjs'; import { debounceTime, mergeMap } from 'rxjs/operators import { http, HttpRequest } from 'observable-http-lib'; // grab textarea reference const myTextarea = document.getElementById('myTextarea'); // create an observable of textarea inputs const eventSource = fromEvent(myTextarea, 'input'); // only send http request once user has stopped typing for 500ms const subscription = eventSource .pipe( debounceTime(500), mergeMap((event) => http.request(new HttpRequest('POST', '/my_endpoint', { data: event.data })) ) ) .subscribe((res) => console.log(`success: ${res}`), (err) => console.log(`fail: ${err}`));
  • 17. Shameless plug: spread the word about MyMahi (mymahi.co.nz), it’ll keep me employed, please. PLEASE. PLEASE!!!! FIN

Editor's Notes

  • #2: Introduce yourself and give a quick intro about the presentation, mention that this will be from a javascript context. “Today I will be giving a quick introduction into promises and observables, what they are and how to use them. I will be speaking about these concepts from a JavaScript context.”
  • #3: Mention that we’re starting with Promises
  • #11: Note that there is just too much to cover in a quick intro.