SlideShare a Scribd company logo
Promises in JavaScript
so, async For The Win!
!
!
Leszek Gruchała
@LeszekGruchala
2
The Pyramid of Doom
step1(function(value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// Do something with value4
});
});
});
});
3
Promises to the rescue!
▪ We get
▪ invocation chaining
▪ error propagation
▪ common error handling
▪ common successful result handling
▪ in progress notification (if Promise supports it)
▪ ability to wrap existing async solutions
4
What makes a Promise?
▪ specification Promises/A+ (thenable)
▪ promise.then(onFulfilled, onRejected, onProgress)
▪ Possible states:
▪ fulfilled
▪ rejected
▪ pending
5
Browser support
▪ Q
▪ When.JS
▪ WinJS
▪ RSVP.JS
▪ jQuery 1.8+ (Deferred Object, Promise)
▪ native (!) with Chrome32+, Opera21+, Firefox29+
▪ no Safari & mobile browsers
Examples
7
Native invocation
var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…
if (isOk) {
resolve("Stuff worked!");
} else {
reject(Error("It broke"));
}
});
promise.then(function(result) {
// "Stuff worked!"
}, function(err) {
// Error: "It broke"
});
8
Q - sequence of invocations
Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function(value4) {
// Do something with value4
}).catch(function(error) {
// Handle any error from all above steps, if no catch errors will be thrown to the browser
// and will block JS code execution
}).progress(function() {
//optional notification about progress for promises which support this i.e. file upload
}).finally(function() {
//optional handle success or failure
}).done(function() {
//everything is done, end chain of invocation
});
9
Q - sequence of invocations
//Even if error arises, will wait for other requests to finish
Q.allSettled(promises).then(function(results) {
results.forEach(function(result) {
if (result.state === "fulfilled") {
var value = result.value;
} else {
var reason = result.reason;
}
});
});
10
Q - ‚parallel’ invocations
Q.all(promises).then(function(results) {
results.forEach(function(result) {
if (result.state === "fulfilled") {
var value = result.value;
} else {
var reason = result.reason;
}
});
});
11
Q - wrapping existing solutions (DWR)
function qDwr(dwrFunc, arrayOfParameters) {
var deferred = Q.defer();
if (arrayOfParameters === undefined || arrayOfParameters === null) {
arrayOfParameters = [];
}
arrayOfParameters.push(function(data) {
deferred.notify();
if (data.faulty) {
deferred.reject(data);
} else {
deferred.resolve(data.data);
}
});
dwrFunc.apply(this, arrayOfParameters);
return deferred.promise;
}
12
Q - using existing solutions (DWR)
Q.all([qDwr(Remote.asyncCall), qDwr(Remote.anotherAsyncCall), qDwr(Remote.evenMoreAnotherAsyncCall,
[false])])
//Spread results of all invocations
.spread(function(firstResult, secondResult, thirdResult) {
function render(data, element) {
$(element).html($.Mustache.render("template-id", data));
}
!
render(firstResult, "first-container");
render(secondResult, "second-container");
render(thirdResult, "container-container");
}).progress(function() {
console.log("Notification for each request");
}).catch(function(error) {
//One error handler for everything.
//Without catch, error will be propagated to browser
window.alert(error);
}).done();

More Related Content

PDF
Closures for Java
PDF
NYAN Conference: Debugging asynchronous scenarios in .net
PDF
[grcpp] Refactoring for testability c++
PDF
Serenity Now
PDF
Tddbdd workshop
PPTX
Odoo's Test Framework - Learn Best Practices
PDF
Debugging your varnish instance
PPTX
Introduction to Node.js
Closures for Java
NYAN Conference: Debugging asynchronous scenarios in .net
[grcpp] Refactoring for testability c++
Serenity Now
Tddbdd workshop
Odoo's Test Framework - Learn Best Practices
Debugging your varnish instance
Introduction to Node.js

Viewers also liked (14)

PDF
Practical JavaScript Promises
PPSX
Sexual fantasies for lovers
PDF
TDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
PDF
JavaScript Promises
PPTX
JavaScript Promises
PDF
Boom! Promises/A+ Was Born
PDF
Cloud Platform as a Service: Heroku
PPT
Keeping Promises
PPTX
Promises
PDF
Promises Javascript
PDF
JavaScript Promises
PPT
Feet Under The Blanket
PPTX
Promises, Promises
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Practical JavaScript Promises
Sexual fantasies for lovers
TDC2016POA | Trilha JavaScript - JavaScript Promises na Prática
JavaScript Promises
JavaScript Promises
Boom! Promises/A+ Was Born
Cloud Platform as a Service: Heroku
Keeping Promises
Promises
Promises Javascript
JavaScript Promises
Feet Under The Blanket
Promises, Promises
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Ad

Similar to Javascript Promises (20)

PDF
Javascript Promises/Q Library
PPTX
Async discussion 9_29_15
PPTX
Avoiding callback hell in Node js using promises
PDF
Asynchronous JavaScript and Promises
PDF
Asynchronous development in JavaScript
PDF
Promises - Asynchronous Control Flow
PPT
You promise?
PDF
Getting Comfortable with JS Promises
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PDF
Introduction to Node JS2.pdf
PDF
JavaScript - Promises study notes- 2019-11-30
PDF
Promises - The Unsung Heroes ofJavaScript
PDF
Promises are so passé - Tim Perry - Codemotion Milan 2016
PPTX
Java Script Promise
PDF
Kamil witecki asynchronous, yet readable, code
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
PDF
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
PPTX
The Promised Land (in Angular)
PDF
Unit Testing Express Middleware
PDF
Asynchronous programming done right - Node.js
Javascript Promises/Q Library
Async discussion 9_29_15
Avoiding callback hell in Node js using promises
Asynchronous JavaScript and Promises
Asynchronous development in JavaScript
Promises - Asynchronous Control Flow
You promise?
Getting Comfortable with JS Promises
Async js - Nemetschek Presentaion @ HackBulgaria
Introduction to Node JS2.pdf
JavaScript - Promises study notes- 2019-11-30
Promises - The Unsung Heroes ofJavaScript
Promises are so passé - Tim Perry - Codemotion Milan 2016
Java Script Promise
Kamil witecki asynchronous, yet readable, code
Asynchronous JavaScript Programming with Callbacks & Promises
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
The Promised Land (in Angular)
Unit Testing Express Middleware
Asynchronous programming done right - Node.js
Ad

More from intive (20)

PPTX
Rok z Android MVVM
PDF
Don't Forget About the Layout
PDF
You Don't Need Dependency Injection
PPTX
OWASP Open SAMM
PPTX
Porównanie architektur MVVM i MVC (iOS)
PDF
Wprowadzenie do CoreBluetooth
PDF
.Net anywhere
PDF
Front end - advanced development for beginners
PDF
Kotlin, Spek and tests
PDF
Patronage 2016 Windows 10 Warsztaty
PPTX
Techniczna organizacja zespołu cz 2
PDF
Techniczna organizacja zespołu
PDF
Organizacja zespołu
PDF
Nie tylko C# - Ekosystem Microsoft dla programistów
PDF
[PL] MVP do MVVM - separacja warstw w aplikacji androidowej
PDF
Tips & Tricks Android
PDF
Apple Watch - Getting Started
PDF
Clean architecture: Android
PDF
CoreLocation (iOS) in details
PDF
Developer Job in Practice
Rok z Android MVVM
Don't Forget About the Layout
You Don't Need Dependency Injection
OWASP Open SAMM
Porównanie architektur MVVM i MVC (iOS)
Wprowadzenie do CoreBluetooth
.Net anywhere
Front end - advanced development for beginners
Kotlin, Spek and tests
Patronage 2016 Windows 10 Warsztaty
Techniczna organizacja zespołu cz 2
Techniczna organizacja zespołu
Organizacja zespołu
Nie tylko C# - Ekosystem Microsoft dla programistów
[PL] MVP do MVVM - separacja warstw w aplikacji androidowej
Tips & Tricks Android
Apple Watch - Getting Started
Clean architecture: Android
CoreLocation (iOS) in details
Developer Job in Practice

Recently uploaded (20)

PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
System and Network Administration Chapter 2
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
L1 - Introduction to python Backend.pptx
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
history of c programming in notes for students .pptx
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Introduction to Artificial Intelligence
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PPTX
ai tools demonstartion for schools and inter college
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
System and Network Administration Chapter 2
Adobe Illustrator 28.6 Crack My Vision of Vector Design
L1 - Introduction to python Backend.pptx
Softaken Excel to vCard Converter Software.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
How to Migrate SBCGlobal Email to Yahoo Easily
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
history of c programming in notes for students .pptx
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Digital Systems & Binary Numbers (comprehensive )
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
Which alternative to Crystal Reports is best for small or large businesses.pdf
Introduction to Artificial Intelligence
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Design an Analysis of Algorithms I-SECS-1021-03
VVF-Customer-Presentation2025-Ver1.9.pptx
ai tools demonstartion for schools and inter college
How to Choose the Right IT Partner for Your Business in Malaysia

Javascript Promises

  • 1. Promises in JavaScript so, async For The Win! ! ! Leszek Gruchała @LeszekGruchala
  • 2. 2 The Pyramid of Doom step1(function(value1) { step2(value1, function(value2) { step3(value2, function(value3) { step4(value3, function(value4) { // Do something with value4 }); }); }); });
  • 3. 3 Promises to the rescue! ▪ We get ▪ invocation chaining ▪ error propagation ▪ common error handling ▪ common successful result handling ▪ in progress notification (if Promise supports it) ▪ ability to wrap existing async solutions
  • 4. 4 What makes a Promise? ▪ specification Promises/A+ (thenable) ▪ promise.then(onFulfilled, onRejected, onProgress) ▪ Possible states: ▪ fulfilled ▪ rejected ▪ pending
  • 5. 5 Browser support ▪ Q ▪ When.JS ▪ WinJS ▪ RSVP.JS ▪ jQuery 1.8+ (Deferred Object, Promise) ▪ native (!) with Chrome32+, Opera21+, Firefox29+ ▪ no Safari & mobile browsers
  • 7. 7 Native invocation var promise = new Promise(function(resolve, reject) { // do a thing, possibly async, then… if (isOk) { resolve("Stuff worked!"); } else { reject(Error("It broke")); } }); promise.then(function(result) { // "Stuff worked!" }, function(err) { // Error: "It broke" });
  • 8. 8 Q - sequence of invocations Q.fcall(promisedStep1) .then(promisedStep2) .then(promisedStep3) .then(promisedStep4) .then(function(value4) { // Do something with value4 }).catch(function(error) { // Handle any error from all above steps, if no catch errors will be thrown to the browser // and will block JS code execution }).progress(function() { //optional notification about progress for promises which support this i.e. file upload }).finally(function() { //optional handle success or failure }).done(function() { //everything is done, end chain of invocation });
  • 9. 9 Q - sequence of invocations //Even if error arises, will wait for other requests to finish Q.allSettled(promises).then(function(results) { results.forEach(function(result) { if (result.state === "fulfilled") { var value = result.value; } else { var reason = result.reason; } }); });
  • 10. 10 Q - ‚parallel’ invocations Q.all(promises).then(function(results) { results.forEach(function(result) { if (result.state === "fulfilled") { var value = result.value; } else { var reason = result.reason; } }); });
  • 11. 11 Q - wrapping existing solutions (DWR) function qDwr(dwrFunc, arrayOfParameters) { var deferred = Q.defer(); if (arrayOfParameters === undefined || arrayOfParameters === null) { arrayOfParameters = []; } arrayOfParameters.push(function(data) { deferred.notify(); if (data.faulty) { deferred.reject(data); } else { deferred.resolve(data.data); } }); dwrFunc.apply(this, arrayOfParameters); return deferred.promise; }
  • 12. 12 Q - using existing solutions (DWR) Q.all([qDwr(Remote.asyncCall), qDwr(Remote.anotherAsyncCall), qDwr(Remote.evenMoreAnotherAsyncCall, [false])]) //Spread results of all invocations .spread(function(firstResult, secondResult, thirdResult) { function render(data, element) { $(element).html($.Mustache.render("template-id", data)); } ! render(firstResult, "first-container"); render(secondResult, "second-container"); render(thirdResult, "container-container"); }).progress(function() { console.log("Notification for each request"); }).catch(function(error) { //One error handler for everything. //Without catch, error will be propagated to browser window.alert(error); }).done();