SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
Async JavaScript & Promises/A+
Martin Dimitrov
July 2014
About me
Martin Dimitrov
mdimitrov@nemetschek.bg
Senior Developer Web Technologies, Nemetschek Bulgaria
JavaScript
● The single language available in Modern Web Browsers.
● Full stack Web programming with Node.js
● Single-threaded & Event-driven asynchronous processing
● Jeff Atwood Atwood’s law:
“Any application that can be written in JavaScript will
eventually be written in JavaScript.”
Functions & Callbacks
● Functions are first class citizens in JavaScript
● Functions can accept other functions as parameters and call
them either synchronously or asynchronously.
Callbacks example
$('#saveButton').on('click', function(){
$(this).closest('form').submit();
});
function readJSON(filename, callback) {
fs.readFile(filename, 'utf8', function(err, res) {
if (err) return callback(err);
try {
res = JSON.parse(res);
} catch (ex) {
return callback(ex);
}
callback(null, res);
});
} Pyramid of Doom
step1(function(result1) {
step2(function(result2) {
step3(function(result3) {
// and so on...
});
});
});
Callback Hell
fs.readdir(source, function(err, files) {
if (err) {
console.log('Error finding files: ' + err)
} else {
files.forEach(function(filename, fileIndex) {
console.log(filename)
gm(source + filename).size(function(err, values) {
if (err) {
console.log('Error identifying file size: ' + err)
} else {
console.log(filename + ' : ' + values)
aspect = (values.width / values.height)
widths.forEach(function(width, widthIndex) {
height = Math.round(width / aspect)
console.log('resizing ' + filename + 'to ' + height + 'x' + height)
this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
}.bind(this))
}
})
})
}
});
Example 1
http://codepen.io/sachmata/pen/Hoygz/
for (var i = 1; i <= 3; i++) {
setTimeout(function() {
console.log('async: ' + i);
}, 0);
console.log('sync: ' + i);
}
Example 2
http://codepen.io/sachmata/pen/GrmFE
var start = Date.now();
setTimeout(function() {
var end = Date.now();
console.log('Time elapsed:', end - start, 'ms');
}, 500);
while (Date.now() - start < 1000) {
// do nothing
};
Types of Async Functions
● I/O Functions (XMLHttpRequest)
● Timing Functions (setTimeout, setInterval, setImmediate,
requestAnimationFrame)
● Sometimes-Async Functions (caching)
Error handling in Async Functions
● throw from callback
● try/catch over async function does not work !
setTimeout(function A() {
setTimeout(function B() {
setTimeout(function C() {
throw new Error(
'Something terrible has happened!');
}, 0);
}, 0);
}, 0);
Error: Something terrible has happened!
at Timer.C (/AsyncJS/nestedErrors.js:4:13)
try {
setTimeout(function() {
throw new Error(
'Catch me if you can!');
}, 0);
} catch (e) {
console.error(e);
}
What is a promise? http://www.promisejs.org/
The core idea behind promises is that a promise represents the result of an
asynchronous operation. A promise is in one of three different states:
● pending - The initial state of a promise.
● fulfilled - The state of a promise representing a successful operation.
● rejected - The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it is immutable (i.e. it can never
change again).
Specification Promises/A+ http://promisesaplus.com/ - (thenable) defines
only 'then' method
promise.then(function(result) {
console.log(result); // "Stuff worked!"
}, function(err) {
console.log(err); // Error: "It broke"
});
Browser support
● Q
● when
● WinJS
● RSVP.JS
● jQuery 1.8+ (Deferred object) ! Not Promise/A+ compliant !
● Conformant Implementations of Promises/A+ / Test suite
https://github.com/promises-aplus/promises-spec/blob/master/implementations.md
● ECMAScript 6
jQuery Example (probably you have already used
promises - new ajax module)
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get("example.php", function() {
console.log("success");
}).done(function() {
console.log("second success");
}).fail(function() {
console.log("error");
}).always(function() {
console.log("finished");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
console.log("second finished");
});
Creating jQuery promise
Option 1
function readJSON(filename) {
var task = $.Deferred();
fs.readFile(filename, 'utf8', function(err, res) {
if (err) return task.reject(err);
try {
res = JSON.parse(res);
} catch (ex) {
task.reject(err);
}
task.resolve(res);
});
return task.promise();
}
Option 2
function readJSON(filename) {
return $.Deferred(function(task) {
fs.readFile(filename, 'utf8', function(err, res) {
if (err) return task.reject(err);
try {
res = JSON.parse(res);
} catch (ex) {
task.reject(err);
}
task.resolve(res);
});
}).promise();
}
Other Deferreds in jQuery API
Animations
var dialogPromise = $('#dialog').fadeIn().promise();
dialogPromise.done(afterDialogShown);
Document ready
$(onReady);
$(document).ready(onReady);
$.ready.promise().done(onReady);
What we get from promises?
● Invocation chaining/combining
● Error propagation
● Common error handling
● Common success handling
● Progress notification (if supported)
● Wrap other async solutions
You're Missing the Point of Promises !
http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
Chaining Promises
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// proceed
});
Errors
getJSON("/posts.json").then(function(posts) {
//
}).catch(function(error) {
// since no rejection handler was passed to the
// first `.then`, the error propagates.
});
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// proceed with access to posts and comments
}).catch(function(error) {
// handle errors in either of the two requests
});
Promise with Exception
var userPromise = getUser().then(function(user) {
if (user === null) {
throw new Error('user is null');
}
return user;
}).then(function(user){...}, function(err){...}).done();
Beware of unhandled exceptions/rejections when no reject callback is registered!
Unhandled Exceptions in synchronous code will hit the top of the stack, here might sink
silently. Use 'done' method at the end of Promises chain to signal that any unhandled
exceptions should explode.
try/catch/finally
startSpinner();
getUser('martin')
.then(getProfile)
.then(showProfile)
//.then(errorThrowingFunction)
.catch(displayError)
.finally(stopSpinner)
.done();
Q.all / RSVP.all / $.when / WinJS.Promise
var promise = Q.all([getUser(), getCompany()]).then(function(results) {…});
var promise = $.when(getUser(), getCompany()).then(function(user, company) {…})
var promise = WinJS.Promise.join({
user: getUser(),
company: getCompany()
}).then(function(data) {…}).done();
var promise = WinJS.Promise.any([
getUser(), getCompany()
]).then(function(winner) {…}).done();
Theoreticaly Promises/A+ compliant promises from different implementations can be
mixed, but jQuery promises are not compliant – assimilate as soon as possible.
var realPromise = when(jQueryPromise);
Promises/A+ Performance Hits You Should Be Aware Of
http://thanpol.as/javascript/promises-a-performance-hits-you-should-be-aware-of/
Recommended reads
Async JavaScript: Build More
Responsive Apps with Less Code
by Trevor Burnham
JavaScript: The Good Parts
by Douglas Crockford
Thank you. Questions?

Contenu connexe

Tendances

Refactoring group 1 - chapter 3,4,6
Refactoring   group 1 - chapter 3,4,6Refactoring   group 1 - chapter 3,4,6
Refactoring group 1 - chapter 3,4,6
Duy Lâm
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
Richard Paul
 

Tendances (17)

Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]Writing testable js [by Ted Piotrowski]
Writing testable js [by Ted Piotrowski]
 
Lecture04
Lecture04Lecture04
Lecture04
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Asynchronous JS in Odoo
Asynchronous JS in OdooAsynchronous JS in Odoo
Asynchronous JS in Odoo
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
Tech friday 22.01.2016
Tech friday 22.01.2016Tech friday 22.01.2016
Tech friday 22.01.2016
 
JNI 使用淺談
JNI 使用淺談JNI 使用淺談
JNI 使用淺談
 
Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6Advanced JavaScript - Internship Presentation - Week6
Advanced JavaScript - Internship Presentation - Week6
 
Refactoring group 1 - chapter 3,4,6
Refactoring   group 1 - chapter 3,4,6Refactoring   group 1 - chapter 3,4,6
Refactoring group 1 - chapter 3,4,6
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
Json.parse() in JavaScript
Json.parse() in JavaScriptJson.parse() in JavaScript
Json.parse() in JavaScript
 
Seastar Summit 2019: Past and future of futures
Seastar Summit 2019: Past and future of futuresSeastar Summit 2019: Past and future of futures
Seastar Summit 2019: Past and future of futures
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 

Similaire à Async js - Nemetschek Presentaion @ HackBulgaria

Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
slicejs
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 

Similaire à Async js - Nemetschek Presentaion @ HackBulgaria (20)

非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
You promise?
You promise?You promise?
You promise?
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Promise pattern
Promise patternPromise pattern
Promise pattern
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 

Dernier

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 

Dernier (20)

Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Async js - Nemetschek Presentaion @ HackBulgaria

  • 1. Async JavaScript & Promises/A+ Martin Dimitrov July 2014
  • 2. About me Martin Dimitrov mdimitrov@nemetschek.bg Senior Developer Web Technologies, Nemetschek Bulgaria
  • 3. JavaScript ● The single language available in Modern Web Browsers. ● Full stack Web programming with Node.js ● Single-threaded & Event-driven asynchronous processing ● Jeff Atwood Atwood’s law: “Any application that can be written in JavaScript will eventually be written in JavaScript.” Functions & Callbacks ● Functions are first class citizens in JavaScript ● Functions can accept other functions as parameters and call them either synchronously or asynchronously.
  • 4. Callbacks example $('#saveButton').on('click', function(){ $(this).closest('form').submit(); }); function readJSON(filename, callback) { fs.readFile(filename, 'utf8', function(err, res) { if (err) return callback(err); try { res = JSON.parse(res); } catch (ex) { return callback(ex); } callback(null, res); }); } Pyramid of Doom step1(function(result1) { step2(function(result2) { step3(function(result3) { // and so on... }); }); });
  • 5. Callback Hell fs.readdir(source, function(err, files) { if (err) { console.log('Error finding files: ' + err) } else { files.forEach(function(filename, fileIndex) { console.log(filename) gm(source + filename).size(function(err, values) { if (err) { console.log('Error identifying file size: ' + err) } else { console.log(filename + ' : ' + values) aspect = (values.width / values.height) widths.forEach(function(width, widthIndex) { height = Math.round(width / aspect) console.log('resizing ' + filename + 'to ' + height + 'x' + height) this.resize(width, height).write(destination + 'w' + width + '_' + filename, function(err) { if (err) console.log('Error writing file: ' + err) }) }.bind(this)) } }) }) } });
  • 6. Example 1 http://codepen.io/sachmata/pen/Hoygz/ for (var i = 1; i <= 3; i++) { setTimeout(function() { console.log('async: ' + i); }, 0); console.log('sync: ' + i); } Example 2 http://codepen.io/sachmata/pen/GrmFE var start = Date.now(); setTimeout(function() { var end = Date.now(); console.log('Time elapsed:', end - start, 'ms'); }, 500); while (Date.now() - start < 1000) { // do nothing };
  • 7.
  • 8. Types of Async Functions ● I/O Functions (XMLHttpRequest) ● Timing Functions (setTimeout, setInterval, setImmediate, requestAnimationFrame) ● Sometimes-Async Functions (caching) Error handling in Async Functions ● throw from callback ● try/catch over async function does not work ! setTimeout(function A() { setTimeout(function B() { setTimeout(function C() { throw new Error( 'Something terrible has happened!'); }, 0); }, 0); }, 0); Error: Something terrible has happened! at Timer.C (/AsyncJS/nestedErrors.js:4:13) try { setTimeout(function() { throw new Error( 'Catch me if you can!'); }, 0); } catch (e) { console.error(e); }
  • 9. What is a promise? http://www.promisejs.org/ The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states: ● pending - The initial state of a promise. ● fulfilled - The state of a promise representing a successful operation. ● rejected - The state of a promise representing a failed operation. Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again). Specification Promises/A+ http://promisesaplus.com/ - (thenable) defines only 'then' method promise.then(function(result) { console.log(result); // "Stuff worked!" }, function(err) { console.log(err); // Error: "It broke" });
  • 10. Browser support ● Q ● when ● WinJS ● RSVP.JS ● jQuery 1.8+ (Deferred object) ! Not Promise/A+ compliant ! ● Conformant Implementations of Promises/A+ / Test suite https://github.com/promises-aplus/promises-spec/blob/master/implementations.md ● ECMAScript 6
  • 11. jQuery Example (probably you have already used promises - new ajax module) // Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.get("example.php", function() { console.log("success"); }).done(function() { console.log("second success"); }).fail(function() { console.log("error"); }).always(function() { console.log("finished"); }); // Perform other work here ... // Set another completion function for the request above jqxhr.always(function() { console.log("second finished"); });
  • 12. Creating jQuery promise Option 1 function readJSON(filename) { var task = $.Deferred(); fs.readFile(filename, 'utf8', function(err, res) { if (err) return task.reject(err); try { res = JSON.parse(res); } catch (ex) { task.reject(err); } task.resolve(res); }); return task.promise(); } Option 2 function readJSON(filename) { return $.Deferred(function(task) { fs.readFile(filename, 'utf8', function(err, res) { if (err) return task.reject(err); try { res = JSON.parse(res); } catch (ex) { task.reject(err); } task.resolve(res); }); }).promise(); }
  • 13. Other Deferreds in jQuery API Animations var dialogPromise = $('#dialog').fadeIn().promise(); dialogPromise.done(afterDialogShown); Document ready $(onReady); $(document).ready(onReady); $.ready.promise().done(onReady);
  • 14. What we get from promises? ● Invocation chaining/combining ● Error propagation ● Common error handling ● Common success handling ● Progress notification (if supported) ● Wrap other async solutions You're Missing the Point of Promises ! http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/
  • 15. Chaining Promises getJSON("/posts.json").then(function(json) { return json.post; }).then(function(post) { // proceed }); Errors getJSON("/posts.json").then(function(posts) { // }).catch(function(error) { // since no rejection handler was passed to the // first `.then`, the error propagates. }); getJSON("/post/1.json").then(function(post) { return getJSON(post.commentURL); }).then(function(comments) { // proceed with access to posts and comments }).catch(function(error) { // handle errors in either of the two requests });
  • 16. Promise with Exception var userPromise = getUser().then(function(user) { if (user === null) { throw new Error('user is null'); } return user; }).then(function(user){...}, function(err){...}).done(); Beware of unhandled exceptions/rejections when no reject callback is registered! Unhandled Exceptions in synchronous code will hit the top of the stack, here might sink silently. Use 'done' method at the end of Promises chain to signal that any unhandled exceptions should explode.
  • 17. try/catch/finally startSpinner(); getUser('martin') .then(getProfile) .then(showProfile) //.then(errorThrowingFunction) .catch(displayError) .finally(stopSpinner) .done(); Q.all / RSVP.all / $.when / WinJS.Promise var promise = Q.all([getUser(), getCompany()]).then(function(results) {…}); var promise = $.when(getUser(), getCompany()).then(function(user, company) {…}) var promise = WinJS.Promise.join({ user: getUser(), company: getCompany() }).then(function(data) {…}).done(); var promise = WinJS.Promise.any([ getUser(), getCompany() ]).then(function(winner) {…}).done();
  • 18. Theoreticaly Promises/A+ compliant promises from different implementations can be mixed, but jQuery promises are not compliant – assimilate as soon as possible. var realPromise = when(jQueryPromise); Promises/A+ Performance Hits You Should Be Aware Of http://thanpol.as/javascript/promises-a-performance-hits-you-should-be-aware-of/
  • 19. Recommended reads Async JavaScript: Build More Responsive Apps with Less Code by Trevor Burnham JavaScript: The Good Parts by Douglas Crockford