SlideShare a Scribd company logo
2
Contents
1. Introduction
2. Asynchronous processing in JavaScript
3. Callbacks & Callback hell
4. Promises arrive in JavaScript!
5. Constructing a Promise
6. Promise states
7. Promises chaining & transformation
8. Error handling
9. Promise.all() & Promise.race()
10. Summary
Most read
3
Introduction
JavaScript is a single-threaded and asynchronous programming language.
one thread == one call stack == one thing at a time
Most read
11
Promise states
A Promise is in one of these 3 states:
 pending: initial state, neither fulfilled nor rejected.
 fulfilled: meaning that the operation completed successfully.
 rejected: meaning that the operation failed.
Most read
Callbacks & Promises in JS
Presentation by
Hung Nguyen Huy
Contents
1. Introduction
2. Asynchronous processing in JavaScript
3. Callbacks & Callback hell
4. Promises arrive in JavaScript!
5. Constructing a Promise
6. Promise states
7. Promises chaining & transformation
8. Error handling
9. Promise.all() & Promise.race()
10. Summary
Introduction
JavaScript is a single-threaded and asynchronous programming language.
one thread == one call stack == one thing at a time
Asynchronous vs Synchronous
 Synchronous Processing
In synchronous programs, if you have two lines of code (L1 followed by L2), then L2
can not begin running until L1 has finished executing.
 Asynchronous Processing
In asynchronous programs, you can have two lines of code (L1 followed by L2),
where L1 schedules some task to be run in the future, but L2 runs before that task
completes.
Asynchronous vs Synchronous
Synchronous Asynchronous
Callbacks
A callback function is a function passed into another function as an argument,
which is then invoked inside the outer function to complete some kind of
routine or action.
Async callbacks & Callback hell
 Asynchronous callback
Callbacks are often used to continue code execution after
an asynchronous operation has completed - these are called asynchronous
callbacks.
 Callback hell
Chain of asynchronous operations
=> Hard to read & debug code.
Promises arrive in JavaScript!
Getting rid of callback hell!
What is Promise?
Promise is an object which represents the eventual completion or failure of an
asynchronous operation, and its resulting value.
Constructing a Promise
 We use new Promise to construct the
promise
 We give the constructor a executor function
which does the actual work.
 Executor function is passed with 2
arguments: resolve and reject functions.
 Resolve function fulfills the promise and
reject function rejects the promise.
new Promise(
/* executor */
function(resolve, reject) {
...
}
);
Promise states
A Promise is in one of these 3 states:
 pending: initial state, neither fulfilled nor rejected.
 fulfilled: meaning that the operation completed successfully.
 rejected: meaning that the operation failed.
Using the Promise object
 A pending promise can either be fulfilled with a value, or rejected with a
reason (error).
 When either of these options happens, the associated handlers queued
up by a promise's then method are called.
then() and catch()
 then()
Takes up to two arguments: callback
functions for the success and failure cases of
the Promise. It returns a Promise.
p.then(onFulfilled[, onRejected]);
p.then(function(value) {
// fulfillment
}, function(reason) {
// rejection
});
 catch()
Take only one argument to deal with rejected
cases only. It returns a Promise.
p.catch(onRejected);
p.catch(function(reason) {
// rejection
});
Promises chaining & transformation
As the then() and catch() methods return promises, they can be chained.
Error handling
 with then()  with catch()
get('story.json').then(function(response) {
console.log("Success!", response);
}, function(error) {
console.log("Failed!", error);
})
get('story.json').then(function(response) {
console.log("Success!", response);
}).catch(function(error) {
console.log("Failed!", error);
})
get('story.json').then(function(response) {
console.log("Success!", response);
}).then(undefined, function(error) {
console.log("Failed!", error);
})
Error handling
 Different between then(undefined, func) and catch(func)?
Promise rejections skip forward to the next then() with a rejection callback (or
catch()).
With then(func1, func2), func1 or func2 will be called, never both. But with
then(func1).catch(func2), both will be called if func1 rejects, as they're separate
steps in the chain.
Error handling
asyncThing1().then(function() {
return asyncThing2();
}).then(function() {
return asyncThing3();
}).catch(function(err) {
return asyncRecovery1();
}).then(function() {
return asyncThing4();
}, function(err) {
return asyncRecovery2();
}).catch(function(err) {
console.log("Don't worry about it");
}).then(function() {
console.log("All done!");
})
Promise.all()
Returns a promise that either fulfills when all of the promises in the iterable
argument have fulfilled or rejects as soon as one of the promises in the
iterable argument rejects.
Promise.race()
Returns a promise that fulfills or rejects as soon as one of the promises in the
iterable fulfills or rejects, with the value or reason from that promise.
SUMMARY

More Related Content

What's hot (20)

Callback Function
Callback FunctionCallback Function
Callback Function
Roland San Nicolas
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
monikadeshmane
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
Samundra khatri
 
Expressjs
ExpressjsExpressjs
Expressjs
Yauheni Nikanovich
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
DivyanshGupta922023
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Derek Willian Stavis
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
Nikolaus Graf
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
Sandi Barr
 
Introduction to Node js
Introduction to Node jsIntroduction to Node js
Introduction to Node js
Akshay Mathur
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
Valeri Karpov
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
manojbkalla
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 
Express JS
Express JSExpress JS
Express JS
Alok Guha
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 

Similar to Asynchronous JavaScript Programming with Callbacks & Promises (20)

JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
Cheryl Yaeger
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique Barcelos
 
Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises
Senthil Kumar
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 
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
Ankit Agarwal
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
The evolution of asynchronous javascript
The evolution of asynchronous javascriptThe evolution of asynchronous javascript
The evolution of asynchronous javascript
Alessandro Cinelli (cirpo)
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
Nishchit Dhanani
 
Promises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScriptPromises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScript
Dean Radcliffe
 
JavaScript - Promises study notes- 2019-11-30
JavaScript  - Promises study notes- 2019-11-30JavaScript  - Promises study notes- 2019-11-30
JavaScript - Promises study notes- 2019-11-30
YangJerng Hwa
 
Utilizing Bluebird Promises
Utilizing Bluebird PromisesUtilizing Bluebird Promises
Utilizing Bluebird Promises
Nicholas van de Walle
 
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise PatternPromises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Christian Lilley
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
Asa Kusuma
 
You promise?
You promise?You promise?
You promise?
IT Weekend
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
eslam_me
 
JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]JavaScript Promises Simplified [Free Meetup]
JavaScript Promises Simplified [Free Meetup]
Haim Michael
 
Async discussion 9_29_15
Async discussion 9_29_15Async discussion 9_29_15
Async discussion 9_29_15
Cheryl Yaeger
 
Avoiding callback hell with promises
Avoiding callback hell with promisesAvoiding callback hell with promises
Avoiding callback hell with promises
TorontoNodeJS
 
Getting Comfortable with JS Promises
Getting Comfortable with JS PromisesGetting Comfortable with JS Promises
Getting Comfortable with JS Promises
Asa Kusuma
 
Asynchronous development in JavaScript
Asynchronous development  in JavaScriptAsynchronous development  in JavaScript
Asynchronous development in JavaScript
Amitai Barnea
 
4 mishchevskii - testing stage18-
4   mishchevskii - testing stage18-4   mishchevskii - testing stage18-
4 mishchevskii - testing stage18-
Ievgenii Katsan
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique Barcelos
 
Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises Asynchronous JavaScript and Promises
Asynchronous JavaScript and Promises
Senthil Kumar
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 
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
Ankit Agarwal
 
Async js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgariaAsync js - Nemetschek Presentaion @ HackBulgaria
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
Nishchit Dhanani
 
Promises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScriptPromises - The Unsung Heroes ofJavaScript
Promises - The Unsung Heroes ofJavaScript
Dean Radcliffe
 
JavaScript - Promises study notes- 2019-11-30
JavaScript  - Promises study notes- 2019-11-30JavaScript  - Promises study notes- 2019-11-30
JavaScript - Promises study notes- 2019-11-30
YangJerng Hwa
 
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise PatternPromises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Christian Lilley
 
Practical JavaScript Promises
Practical JavaScript PromisesPractical JavaScript Promises
Practical JavaScript Promises
Asa Kusuma
 
JavaScript promise
JavaScript promiseJavaScript promise
JavaScript promise
eslam_me
 
Ad

Recently uploaded (20)

Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)Shell Skill Tree - LabEx Certification (LabEx)
Shell Skill Tree - LabEx Certification (LabEx)
VICTOR MAESTRE RAMIREZ
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Plooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your wayPlooma is a writing platform to plan, write, and shape books your way
Plooma is a writing platform to plan, write, and shape books your way
Plooma
 
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdfThe Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
The Future of Open Source Reporting Best Alternatives to Jaspersoft.pdf
Varsha Nayak
 
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps CyclesFrom Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
From Chaos to Clarity - Designing (AI-Ready) APIs with APIOps Cycles
Marjukka Niinioja
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across IndustriesArtificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Who will create the languages of the future?
Who will create the languages of the future?Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native BarcelonaOpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage OverlookCode and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlowDevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Ad

Asynchronous JavaScript Programming with Callbacks & Promises

  • 1. Callbacks & Promises in JS Presentation by Hung Nguyen Huy
  • 2. Contents 1. Introduction 2. Asynchronous processing in JavaScript 3. Callbacks & Callback hell 4. Promises arrive in JavaScript! 5. Constructing a Promise 6. Promise states 7. Promises chaining & transformation 8. Error handling 9. Promise.all() & Promise.race() 10. Summary
  • 3. Introduction JavaScript is a single-threaded and asynchronous programming language. one thread == one call stack == one thing at a time
  • 4. Asynchronous vs Synchronous  Synchronous Processing In synchronous programs, if you have two lines of code (L1 followed by L2), then L2 can not begin running until L1 has finished executing.  Asynchronous Processing In asynchronous programs, you can have two lines of code (L1 followed by L2), where L1 schedules some task to be run in the future, but L2 runs before that task completes.
  • 6. Callbacks A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
  • 7. Async callbacks & Callback hell  Asynchronous callback Callbacks are often used to continue code execution after an asynchronous operation has completed - these are called asynchronous callbacks.  Callback hell Chain of asynchronous operations => Hard to read & debug code.
  • 8. Promises arrive in JavaScript! Getting rid of callback hell!
  • 9. What is Promise? Promise is an object which represents the eventual completion or failure of an asynchronous operation, and its resulting value.
  • 10. Constructing a Promise  We use new Promise to construct the promise  We give the constructor a executor function which does the actual work.  Executor function is passed with 2 arguments: resolve and reject functions.  Resolve function fulfills the promise and reject function rejects the promise. new Promise( /* executor */ function(resolve, reject) { ... } );
  • 11. Promise states A Promise is in one of these 3 states:  pending: initial state, neither fulfilled nor rejected.  fulfilled: meaning that the operation completed successfully.  rejected: meaning that the operation failed.
  • 12. Using the Promise object  A pending promise can either be fulfilled with a value, or rejected with a reason (error).  When either of these options happens, the associated handlers queued up by a promise's then method are called.
  • 13. then() and catch()  then() Takes up to two arguments: callback functions for the success and failure cases of the Promise. It returns a Promise. p.then(onFulfilled[, onRejected]); p.then(function(value) { // fulfillment }, function(reason) { // rejection });  catch() Take only one argument to deal with rejected cases only. It returns a Promise. p.catch(onRejected); p.catch(function(reason) { // rejection });
  • 14. Promises chaining & transformation As the then() and catch() methods return promises, they can be chained.
  • 15. Error handling  with then()  with catch() get('story.json').then(function(response) { console.log("Success!", response); }, function(error) { console.log("Failed!", error); }) get('story.json').then(function(response) { console.log("Success!", response); }).catch(function(error) { console.log("Failed!", error); }) get('story.json').then(function(response) { console.log("Success!", response); }).then(undefined, function(error) { console.log("Failed!", error); })
  • 16. Error handling  Different between then(undefined, func) and catch(func)? Promise rejections skip forward to the next then() with a rejection callback (or catch()). With then(func1, func2), func1 or func2 will be called, never both. But with then(func1).catch(func2), both will be called if func1 rejects, as they're separate steps in the chain.
  • 17. Error handling asyncThing1().then(function() { return asyncThing2(); }).then(function() { return asyncThing3(); }).catch(function(err) { return asyncRecovery1(); }).then(function() { return asyncThing4(); }, function(err) { return asyncRecovery2(); }).catch(function(err) { console.log("Don't worry about it"); }).then(function() { console.log("All done!"); })
  • 18. Promise.all() Returns a promise that either fulfills when all of the promises in the iterable argument have fulfilled or rejects as soon as one of the promises in the iterable argument rejects.
  • 19. Promise.race() Returns a promise that fulfills or rejects as soon as one of the promises in the iterable fulfills or rejects, with the value or reason from that promise.