2
Most read
3
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

PDF
Intro to Asynchronous Javascript
PPTX
Introduction to Node.js
PDF
Basics of JavaScript
PDF
Asynchronous JavaScript Programming
PPTX
React js
PPTX
The Internet
PDF
Spring Data JPA
PDF
JavaScript - Chapter 6 - Basic Functions
Intro to Asynchronous Javascript
Introduction to Node.js
Basics of JavaScript
Asynchronous JavaScript Programming
React js
The Internet
Spring Data JPA
JavaScript - Chapter 6 - Basic Functions

What's hot (20)

PDF
React js
PDF
Callback Function
PPTX
Express js
PPTX
JS Event Loop
PPTX
What is component in reactjs
PDF
ReactJS presentation
PPTX
Angular modules in depth
PPTX
React JS: A Secret Preview
PDF
Understanding react hooks
PPTX
Introduction to React JS for beginners
PPTX
JavaScript Promises
PDF
JavaScript guide 2020 Learn JavaScript
PPTX
reactJS
PPTX
Modern JS with ES6
PPT
Css Ppt
PPTX
Intro to React
PPTX
Rest api with node js and express
PPTX
Express JS
PDF
Workshop 21: React Router
React js
Callback Function
Express js
JS Event Loop
What is component in reactjs
ReactJS presentation
Angular modules in depth
React JS: A Secret Preview
Understanding react hooks
Introduction to React JS for beginners
JavaScript Promises
JavaScript guide 2020 Learn JavaScript
reactJS
Modern JS with ES6
Css Ppt
Intro to React
Rest api with node js and express
Express JS
Workshop 21: React Router
Ad

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

PDF
Introduction to Node JS2.pdf
PDF
Promises - Asynchronous Control Flow
PPTX
Async discussion 9_29_15
PDF
Getting Comfortable with JS Promises
PDF
Avoiding callback hell with promises
PDF
Promises look into the async future
PDF
Javascript Promises/Q Library
PDF
Asynchronous development in JavaScript
PPTX
Avoiding callback hell in Node js using promises
PDF
Java Script Basics presentation of program
PDF
JavaScript Interview Questions 2023
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
PPTX
ES2015 promise
PDF
Advanced JavaScript - Internship Presentation - Week6
PPTX
Promises, promises, and then observables
PDF
Asynchronous Programming. Talk from ESUG2024
PDF
How To Use IO Monads in Scala?
PDF
Javascript internals
PPTX
Cordova training : Day 3 - Introduction to Javascript
PPTX
Javascripts hidden treasures BY - https://geekyants.com/
Introduction to Node JS2.pdf
Promises - Asynchronous Control Flow
Async discussion 9_29_15
Getting Comfortable with JS Promises
Avoiding callback hell with promises
Promises look into the async future
Javascript Promises/Q Library
Asynchronous development in JavaScript
Avoiding callback hell in Node js using promises
Java Script Basics presentation of program
JavaScript Interview Questions 2023
Async js - Nemetschek Presentaion @ HackBulgaria
ES2015 promise
Advanced JavaScript - Internship Presentation - Week6
Promises, promises, and then observables
Asynchronous Programming. Talk from ESUG2024
How To Use IO Monads in Scala?
Javascript internals
Cordova training : Day 3 - Introduction to Javascript
Javascripts hidden treasures BY - https://geekyants.com/
Ad

Recently uploaded (20)

PPTX
MCP empowers AI Agents from Zero to Production
PPTX
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
PPTX
SAP Business AI_L1 Overview_EXTERNAL.pptx
PDF
What Makes a Great Data Visualization Consulting Service.pdf
PPTX
Comprehensive Guide to Digital Image Processing Concepts and Applications
PPTX
Post-Migration Optimization Playbook: Getting the Most Out of Your New Adobe ...
PPTX
UNIT II: Software design, software .pptx
PDF
Coding with GPT-5- What’s New in GPT 5 That Benefits Developers.pdf
PPTX
Swiggy API Scraping A Comprehensive Guide on Data Sets and Applications.pptx
PPTX
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
PPTX
Beige and Black Minimalist Project Deck Presentation (1).pptx
PPTX
Presentation - Summer Internship at Samatrix.io_template_2.pptx
PPTX
FLIGHT TICKET API | API INTEGRATION PLATFORM
PDF
Mobile App Backend Development with WordPress REST API: The Complete eBook
PDF
infoteam HELLAS company profile 2025 presentation
PDF
Ragic Data Security Overview: Certifications, Compliance, and Network Safegua...
PPTX
HackYourBrain__UtrechtJUG__11092025.pptx
PDF
Top 10 Project Management Software for Small Teams in 2025.pdf
PDF
solman-7.0-ehp1-sp21-incident-management
PDF
Mobile App for Guard Tour and Reporting.pdf
MCP empowers AI Agents from Zero to Production
DevOpsDays Halifax 2025 - Building 10x Organizations Using Modern Productivit...
SAP Business AI_L1 Overview_EXTERNAL.pptx
What Makes a Great Data Visualization Consulting Service.pdf
Comprehensive Guide to Digital Image Processing Concepts and Applications
Post-Migration Optimization Playbook: Getting the Most Out of Your New Adobe ...
UNIT II: Software design, software .pptx
Coding with GPT-5- What’s New in GPT 5 That Benefits Developers.pdf
Swiggy API Scraping A Comprehensive Guide on Data Sets and Applications.pptx
Bandicam Screen Recorder 8.2.1 Build 2529 Crack
Beige and Black Minimalist Project Deck Presentation (1).pptx
Presentation - Summer Internship at Samatrix.io_template_2.pptx
FLIGHT TICKET API | API INTEGRATION PLATFORM
Mobile App Backend Development with WordPress REST API: The Complete eBook
infoteam HELLAS company profile 2025 presentation
Ragic Data Security Overview: Certifications, Compliance, and Network Safegua...
HackYourBrain__UtrechtJUG__11092025.pptx
Top 10 Project Management Software for Small Teams in 2025.pdf
solman-7.0-ehp1-sp21-incident-management
Mobile App for Guard Tour and Reporting.pdf

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.