SlideShare a Scribd company logo
2
Most read
4
Most read
11
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

PPTX
JS Event Loop
PDF
Asynchronous JavaScript Programming
PDF
Intro to Asynchronous Javascript
PPTX
JavaScript Event Loop
PDF
JavaScript - Chapter 15 - Debugging Techniques
PDF
JavaScript - Chapter 8 - Objects
PPTX
Introduction to Node js
PPTX
Node js Introduction
JS Event Loop
Asynchronous JavaScript Programming
Intro to Asynchronous Javascript
JavaScript Event Loop
JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 8 - Objects
Introduction to Node js
Node js Introduction

What's hot (20)

PPTX
JavaScript Promises
PDF
Callback Function
PPTX
Basic Concept of Node.js & NPM
PPT
JavaScript & Dom Manipulation
PPT
jQuery Ajax
ODP
Introduction to ReactJS
PDF
javascript objects
PPTX
React js
PPTX
What Is Express JS?
PDF
Workshop 21: React Router
PPTX
Introduction to React JS for beginners
PPT
Introduction to Javascript
PPT
Php with MYSQL Database
PPTX
Introduction to JavaScript Basics.
PDF
Asynchronous javascript
PPT
Java Script ppt
PPTX
Introduction to Node.js
PPT
JavaScript: Events Handling
PDF
The New JavaScript: ES6
PPTX
Spring Boot and REST API
JavaScript Promises
Callback Function
Basic Concept of Node.js & NPM
JavaScript & Dom Manipulation
jQuery Ajax
Introduction to ReactJS
javascript objects
React js
What Is Express JS?
Workshop 21: React Router
Introduction to React JS for beginners
Introduction to Javascript
Php with MYSQL Database
Introduction to JavaScript Basics.
Asynchronous javascript
Java Script ppt
Introduction to Node.js
JavaScript: Events Handling
The New JavaScript: ES6
Spring Boot and REST API
Ad

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

PDF
Introduction to Node JS2.pdf
PDF
JavaScript Promises Simplified [Free Meetup]
PPTX
Async discussion 9_29_15
PDF
Avoiding callback hell with promises
PDF
Getting Comfortable with JS Promises
PDF
Asynchronous development in JavaScript
PDF
4 mishchevskii - testing stage18-
PDF
Promises - Asynchronous Control Flow
PDF
Asynchronous JavaScript and Promises
PPTX
Java Script Promise
PPTX
Avoiding callback hell in Node js using promises
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PDF
The evolution of asynchronous javascript
PDF
Async History - javascript
PDF
Promises - The Unsung Heroes ofJavaScript
PDF
JavaScript - Promises study notes- 2019-11-30
PDF
Utilizing Bluebird Promises
PDF
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
PDF
Practical JavaScript Promises
PPT
You promise?
Introduction to Node JS2.pdf
JavaScript Promises Simplified [Free Meetup]
Async discussion 9_29_15
Avoiding callback hell with promises
Getting Comfortable with JS Promises
Asynchronous development in JavaScript
4 mishchevskii - testing stage18-
Promises - Asynchronous Control Flow
Asynchronous JavaScript and Promises
Java Script Promise
Avoiding callback hell in Node js using promises
Async js - Nemetschek Presentaion @ HackBulgaria
The evolution of asynchronous javascript
Async History - javascript
Promises - The Unsung Heroes ofJavaScript
JavaScript - Promises study notes- 2019-11-30
Utilizing Bluebird Promises
Promises, Promises: Mastering Async I/O in Javascript with the Promise Pattern
Practical JavaScript Promises
You promise?
Ad

Recently uploaded (20)

PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
DOCX
The Five Best AI Cover Tools in 2025.docx
PDF
top salesforce developer skills in 2025.pdf
PDF
AI in Product Development-omnex systems
PDF
Convert Thunderbird to Outlook into bulk
PDF
Jenkins: An open-source automation server powering CI/CD Automation
PPTX
How a Careem Clone App Allows You to Compete with Large Mobility Brands
PDF
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
PDF
A REACT POMODORO TIMER WEB APPLICATION.pdf
PDF
Build Multi-agent using Agent Development Kit
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
PDF
System and Network Administraation Chapter 3
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
PDF
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
PPTX
Materi_Pemrograman_Komputer-Looping.pptx
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
PDF
Become an Agentblazer Champion Challenge Kickoff
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
System and Network Administration Chapter 2
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
The Five Best AI Cover Tools in 2025.docx
top salesforce developer skills in 2025.pdf
AI in Product Development-omnex systems
Convert Thunderbird to Outlook into bulk
Jenkins: An open-source automation server powering CI/CD Automation
How a Careem Clone App Allows You to Compete with Large Mobility Brands
Understanding NFT Marketplace Development_ Trends and Innovations.pdf
A REACT POMODORO TIMER WEB APPLICATION.pdf
Build Multi-agent using Agent Development Kit
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
System and Network Administraation Chapter 3
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
How to Choose the Most Effective Social Media Agency in Bangalore.pdf
Materi_Pemrograman_Komputer-Looping.pptx
The Role of Automation and AI in EHS Management for Data Centers.pdf
Become an Agentblazer Champion Challenge Kickoff
How to Migrate SBCGlobal Email to Yahoo Easily
System and Network Administration Chapter 2

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.