SlideShare a Scribd company logo
The Evolution of JavaScript Asynchronous Calls
Pham Huy Hoang - Harry Pham
Github: conanak99
Agenda
How we deal with asynchronous call in JS
1. Innocent Callback and callback hell
2. Promise all the things
3. The magic of async/await
JS is single-threaded
● JS has a single Call Stack => Can only do one thing at a time.
● While the Call Stack has functions to execute, the browser can’t actually
do anything else  => Browser hang and laggy UI
● Solution: Asynchronous Call
This demo will hang the browser
1. The innocent Callback
● Functions are first-class objects
● We can pass a function as an argument in another function
● Later execute that passed-in function at convenience time
jQuery callback style
$(document).ready(function() {
$('#button').on('click', function(event) {
$.getJSON('/data.json', function(data) {
console.log(data);
});
});
});
Demo: https://codepen.io/huyhoangpham/pen/veGYrw?editors=1010#0
Callback hells
getData(function(a) {
getMoreData(function(b) {
getMoreData(function(c) {
getMoreData(function(d) {
getMoreData(function(e) {
// do something
});
});
});
});
})
https://codepen.io/huyhoangpham/pen/VMaYwo?editors=1010
The downside
● Make code difficult to maintain and debug
● Exception handling is … tedious
● Anonymous inline function = hard-to-read call stack
2. Promise all the things
● Represents the eventual result of an asynchronous operation.
● Must be in one of three states: pending, fulfilled, or rejected.
Resolve and reject
const promise = new Promise((resolve, reject) => {
// do async stuff
resolve('DONE!');
});
promise.then((result) => {
console.log(result); // result will be 'DONE!'
});
Demo:
https://codepen.io/huyhoangpham/pen/gGrbMM?editors=1010
const promise = new Promise((resolve, reject) =>
{
// do async stuff
reject(new Error('FAIL!'));
});
promise
.then((result) => {
// Will not be called
})
.catch((error) => {
console.log(error); // FAIL!
})
Chaining promises
function getData(input) {
return Promise.resolve(input + ' data');
}
getData('hello')
.then((result) => {
return result + ' chain promise';
// result: 'hello data'
})
.then((result2) => {
console.log(result2);
// result2: 'hello data chain promise'
})
Demo: https://codepen.io/huyhoangpham/pen/GMZgrq?editors=1010
getData('hello')
.then((result) => {
throw new Error('Oops');
})
.then((result2) => {
return result2;
})
.then((result3) => {
return result3;
})
.catch((error) => {
console.log(error); //oops
})
How promise solve callback hell
getData(function(a) {
getMoreData(function(b) {
getMoreData(function(c) {
getMoreData(function(d) {
getMoreData(function(e) {
// do something
});
});
});
});
})
getData()
.then(getMoreData)
.then(getMoreData)
.then(getMoreData)
.then(getMoreData)
.then((result) => {
// do something
})
.catch((error) => {
handleError(error);
});
So you want parallel call?
Promise.all([
firstAsyncCall(),
secondAsyncCall(),
lastAsyncCall(),
])
.then(result => {
firstAsyncCallResult = result[0];
secondAsyncCallResult = result[1];
lastAsyncCallResult = result[2];
});
Demo: https://codepen.io/huyhoangpham/pen/YrqPVy?editors=1010
Pitfall (Promise hell and error handling)
getData.then(() => {
getMoreData.then(()=> {
getMoreDate.then(() => {
// Do something
});
});
});
promise.then(resolve, reject);
promise.then(
(result) => {
// Do something
throw new Error('This error will not be
caught');
},
(error) => {
console.log(error);
});
Why promise
● Cleaner method signatures -> Easier to
read
● Easier to write function and test -> Reduce
cost of maintenance
● It allows for chaining of promises -> Clear
and shorter code
Let’s rest for 20 seconds
The magic of async/await (ES7)
Treat functions returning Promise objects as if
they were synchronous
$('#request').click(async () => {
const imgUrl = await findRandomImgPromise('cat');
$('#cat').attr('src', imgUrl);
});
https://codepen.io/huyhoangpham/pen/aLNzLr?editors=1010
Make asynchronous code easy again
getData(function(a) {
getMoreData(function(b) {
getMoreData(function(c) {
getMoreData(function(d) {
getMoreData(function(e) {
// do something
});
});
});
});
})
async function doGreatThing() {
try {
const firstData = await getData();
const secondData = await getMoreData(firstData);
const thirdData = await getMoreDate(secondData);
// How about parallel call?
const saveResults = await Promise.all([
saveData(firstData),
saveData(secondData),
saveData(thirdData)]);
} catch (error) {
console.log(error);
}
}
Magic time, oops… demo time
● Sequential: https://codepen.io/huyhoangpham/pen/VMaYxe?editors=1010
● Parellel: https://codepen.io/huyhoangpham/pen/JrXdXK?editors=1010
● Looping: https://codepen.io/huyhoangpham/pen/rGeaXX?editors=1010
Everything look … synchronous
● Await keyword is only available in a async function
● No more callback, then, or catch => Cleaner code
● Easier to debug
● Easy looping and error try/catch
=> Everything look … synchronous
How about old browsers?
● Use babel transpiler
● Behind the scene:
● Generate a state machine
Looking back
We have came a long way
● From Callback to Promise(ES6) to Async/Await(ES7)
● Callback is still used for event, but should not for
asynchronous call
● Should have a good understanding on Promise
● Use async/await if possible. It makes our life better
JS Code Combo
1. Use bluebird to turn callback into promise
2. Use the magic of async/await
Thank you for listening!

More Related Content

What's hot (20)

PDF
Callbacks and control flow in Node js
Thomas Roch
 
PDF
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
PDF
Even more java script best practices
ChengHui Weng
 
PDF
JavaScript Promise
Joseph Chiang
 
PPTX
Promises, promises, and then observables
Stefan Charsley
 
PDF
Avoiding callback hell with promises
TorontoNodeJS
 
PDF
High Performance web apps in Om, React and ClojureScript
Leonardo Borges
 
PPTX
Java script for web developer
Chalermpon Areepong
 
PDF
Practical JavaScript Promises
Asa Kusuma
 
PPTX
An Introduction to WebWorker - 01.26.12
Digiflare
 
PDF
JavaScript Best Pratices
ChengHui Weng
 
PDF
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
PDF
ActionHeroJS Talk
David Peralta
 
PPTX
Deceptive simplicity of async and await
Andrei Marukovich
 
KEY
Lazy Loading Because I'm Lazy
Johnathan Leppert
 
PDF
Testing in JavaScript
Digital Natives
 
PDF
Promises - Asynchronous Control Flow
Henrique Barcelos
 
PDF
Functional Reactive Programming - RxSwift
Rodrigo Leite
 
PDF
02 Introduction to Javascript
crgwbr
 
PDF
History of jQuery
jeresig
 
Callbacks and control flow in Node js
Thomas Roch
 
Async js - Nemetschek Presentaion @ HackBulgaria
HackBulgaria
 
Even more java script best practices
ChengHui Weng
 
JavaScript Promise
Joseph Chiang
 
Promises, promises, and then observables
Stefan Charsley
 
Avoiding callback hell with promises
TorontoNodeJS
 
High Performance web apps in Om, React and ClojureScript
Leonardo Borges
 
Java script for web developer
Chalermpon Areepong
 
Practical JavaScript Promises
Asa Kusuma
 
An Introduction to WebWorker - 01.26.12
Digiflare
 
JavaScript Best Pratices
ChengHui Weng
 
Functional Reactive Programming / Compositional Event Systems
Leonardo Borges
 
ActionHeroJS Talk
David Peralta
 
Deceptive simplicity of async and await
Andrei Marukovich
 
Lazy Loading Because I'm Lazy
Johnathan Leppert
 
Testing in JavaScript
Digital Natives
 
Promises - Asynchronous Control Flow
Henrique Barcelos
 
Functional Reactive Programming - RxSwift
Rodrigo Leite
 
02 Introduction to Javascript
crgwbr
 
History of jQuery
jeresig
 

Similar to The evolution of java script asynchronous calls (20)

PDF
Async History - javascript
Nishchit Dhanani
 
PPTX
Async discussion 9_29_15
Cheryl Yaeger
 
PPT
You promise?
IT Weekend
 
PDF
Asynchronous development in JavaScript
Amitai Barnea
 
PDF
Intro to Asynchronous Javascript
Garrett Welson
 
PDF
Angular promises and http
Alexe Bogdan
 
PDF
JavaScript, un langage plein de promesses
rfelden
 
PDF
Testing web APIs
FDConf
 
PDF
Asynchronous programming with java script and node.js
Timur Shemsedinov
 
PPTX
The Promised Land (in Angular)
Domenic Denicola
 
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
PPTX
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
PDF
Understanding Asynchronous JavaScript
jnewmanux
 
PPTX
Ecma script
MOHIT KUMAR
 
PDF
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
PDF
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
PDF
Node js
LearningTech
 
PDF
Javascript Promises/Q Library
async_io
 
PDF
Asynchronous JavaScript Programming
Haim Michael
 
PDF
I'm Postal for Promises in Angular
Christian Lilley
 
Async History - javascript
Nishchit Dhanani
 
Async discussion 9_29_15
Cheryl Yaeger
 
You promise?
IT Weekend
 
Asynchronous development in JavaScript
Amitai Barnea
 
Intro to Asynchronous Javascript
Garrett Welson
 
Angular promises and http
Alexe Bogdan
 
JavaScript, un langage plein de promesses
rfelden
 
Testing web APIs
FDConf
 
Asynchronous programming with java script and node.js
Timur Shemsedinov
 
The Promised Land (in Angular)
Domenic Denicola
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
JavaScript Multithread or Single Thread.pptx
RAHITNATH
 
Understanding Asynchronous JavaScript
jnewmanux
 
Ecma script
MOHIT KUMAR
 
Asynchronous JavaScript Programming with Callbacks & Promises
Hùng Nguyễn Huy
 
The evolution of asynchronous JavaScript
Alessandro Cinelli (cirpo)
 
Node js
LearningTech
 
Javascript Promises/Q Library
async_io
 
Asynchronous JavaScript Programming
Haim Michael
 
I'm Postal for Promises in Angular
Christian Lilley
 
Ad

More from Huy Hoàng Phạm (8)

PDF
Live chym kysubrse vs toidicodedao
Huy Hoàng Phạm
 
PDF
Từ Gà Đến Pro Git và GitHub trong 60 phút
Huy Hoàng Phạm
 
PPTX
Hành trình trở thành web đì ve lốp pơ
Huy Hoàng Phạm
 
PPTX
Sinh viên IT học và làm gì để không thất nghiệp
Huy Hoàng Phạm
 
PDF
Từ Sinh Viên IT tới Lập Trình Viên
Huy Hoàng Phạm
 
PDF
The legendary-book
Huy Hoàng Phạm
 
PPTX
IoC and Mapper in C#
Huy Hoàng Phạm
 
PPTX
Slide thuyet trinh
Huy Hoàng Phạm
 
Live chym kysubrse vs toidicodedao
Huy Hoàng Phạm
 
Từ Gà Đến Pro Git và GitHub trong 60 phút
Huy Hoàng Phạm
 
Hành trình trở thành web đì ve lốp pơ
Huy Hoàng Phạm
 
Sinh viên IT học và làm gì để không thất nghiệp
Huy Hoàng Phạm
 
Từ Sinh Viên IT tới Lập Trình Viên
Huy Hoàng Phạm
 
The legendary-book
Huy Hoàng Phạm
 
IoC and Mapper in C#
Huy Hoàng Phạm
 
Slide thuyet trinh
Huy Hoàng Phạm
 
Ad

Recently uploaded (20)

PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
SAP GUI Installation Guide for Windows | Step-by-Step Setup for SAP Access
SAP Vista, an A L T Z E N Company
 
PDF
How AI in Healthcare Apps Can Help You Enhance Patient Care?
Lilly Gracia
 
PPTX
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
PPTX
SAP Public Cloud PPT , SAP PPT, Public Cloud PPT
sonawanekundan2024
 
PDF
Malaysia’s e-Invoice System: A Complete Guide for Businesses
Matiyas Solutions
 
PPTX
TexSender Pro 8.9.1 Crack Full Version Download
cracked shares
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PDF
Troubleshooting Virtual Threads in Java!
Tier1 app
 
PPTX
Farrell__10e_ch04_PowerPoint.pptx Programming Logic and Design slides
bashnahara11
 
PDF
AWS_Agentic_AI_in_Indian_BFSI_A_Strategic_Blueprint_for_Customer.pdf
siddharthnetsavvies
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
PPT
Brief History of Python by Learning Python in three hours
adanechb21
 
PDF
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PPTX
ChessBase 18.02 Crack + Serial Key Free Download
cracked shares
 
PDF
Odoo Customization Services by CandidRoot Solutions
CandidRoot Solutions Private Limited
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
SAP GUI Installation Guide for Windows | Step-by-Step Setup for SAP Access
SAP Vista, an A L T Z E N Company
 
How AI in Healthcare Apps Can Help You Enhance Patient Care?
Lilly Gracia
 
Employee salary prediction using Machine learning Project template.ppt
bhanuk27082004
 
SAP Public Cloud PPT , SAP PPT, Public Cloud PPT
sonawanekundan2024
 
Malaysia’s e-Invoice System: A Complete Guide for Businesses
Matiyas Solutions
 
TexSender Pro 8.9.1 Crack Full Version Download
cracked shares
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
Troubleshooting Virtual Threads in Java!
Tier1 app
 
Farrell__10e_ch04_PowerPoint.pptx Programming Logic and Design slides
bashnahara11
 
AWS_Agentic_AI_in_Indian_BFSI_A_Strategic_Blueprint_for_Customer.pdf
siddharthnetsavvies
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
SAP GUI Installation Guide for macOS (iOS) | Connect to SAP Systems on Mac
SAP Vista, an A L T Z E N Company
 
Brief History of Python by Learning Python in three hours
adanechb21
 
Applitools Platform Pulse: What's New and What's Coming - July 2025
Applitools
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
ChessBase 18.02 Crack + Serial Key Free Download
cracked shares
 
Odoo Customization Services by CandidRoot Solutions
CandidRoot Solutions Private Limited
 

The evolution of java script asynchronous calls

  • 1. The Evolution of JavaScript Asynchronous Calls Pham Huy Hoang - Harry Pham Github: conanak99
  • 2. Agenda How we deal with asynchronous call in JS 1. Innocent Callback and callback hell 2. Promise all the things 3. The magic of async/await
  • 3. JS is single-threaded ● JS has a single Call Stack => Can only do one thing at a time. ● While the Call Stack has functions to execute, the browser can’t actually do anything else  => Browser hang and laggy UI ● Solution: Asynchronous Call This demo will hang the browser
  • 4. 1. The innocent Callback ● Functions are first-class objects ● We can pass a function as an argument in another function ● Later execute that passed-in function at convenience time
  • 5. jQuery callback style $(document).ready(function() { $('#button').on('click', function(event) { $.getJSON('/data.json', function(data) { console.log(data); }); }); }); Demo: https://codepen.io/huyhoangpham/pen/veGYrw?editors=1010#0
  • 6. Callback hells getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d) { getMoreData(function(e) { // do something }); }); }); }); }) https://codepen.io/huyhoangpham/pen/VMaYwo?editors=1010
  • 7. The downside ● Make code difficult to maintain and debug ● Exception handling is … tedious ● Anonymous inline function = hard-to-read call stack
  • 8. 2. Promise all the things ● Represents the eventual result of an asynchronous operation. ● Must be in one of three states: pending, fulfilled, or rejected.
  • 9. Resolve and reject const promise = new Promise((resolve, reject) => { // do async stuff resolve('DONE!'); }); promise.then((result) => { console.log(result); // result will be 'DONE!' }); Demo: https://codepen.io/huyhoangpham/pen/gGrbMM?editors=1010 const promise = new Promise((resolve, reject) => { // do async stuff reject(new Error('FAIL!')); }); promise .then((result) => { // Will not be called }) .catch((error) => { console.log(error); // FAIL! })
  • 10. Chaining promises function getData(input) { return Promise.resolve(input + ' data'); } getData('hello') .then((result) => { return result + ' chain promise'; // result: 'hello data' }) .then((result2) => { console.log(result2); // result2: 'hello data chain promise' }) Demo: https://codepen.io/huyhoangpham/pen/GMZgrq?editors=1010 getData('hello') .then((result) => { throw new Error('Oops'); }) .then((result2) => { return result2; }) .then((result3) => { return result3; }) .catch((error) => { console.log(error); //oops })
  • 11. How promise solve callback hell getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d) { getMoreData(function(e) { // do something }); }); }); }); }) getData() .then(getMoreData) .then(getMoreData) .then(getMoreData) .then(getMoreData) .then((result) => { // do something }) .catch((error) => { handleError(error); });
  • 12. So you want parallel call? Promise.all([ firstAsyncCall(), secondAsyncCall(), lastAsyncCall(), ]) .then(result => { firstAsyncCallResult = result[0]; secondAsyncCallResult = result[1]; lastAsyncCallResult = result[2]; }); Demo: https://codepen.io/huyhoangpham/pen/YrqPVy?editors=1010
  • 13. Pitfall (Promise hell and error handling) getData.then(() => { getMoreData.then(()=> { getMoreDate.then(() => { // Do something }); }); }); promise.then(resolve, reject); promise.then( (result) => { // Do something throw new Error('This error will not be caught'); }, (error) => { console.log(error); });
  • 14. Why promise ● Cleaner method signatures -> Easier to read ● Easier to write function and test -> Reduce cost of maintenance ● It allows for chaining of promises -> Clear and shorter code
  • 15. Let’s rest for 20 seconds
  • 16. The magic of async/await (ES7) Treat functions returning Promise objects as if they were synchronous $('#request').click(async () => { const imgUrl = await findRandomImgPromise('cat'); $('#cat').attr('src', imgUrl); }); https://codepen.io/huyhoangpham/pen/aLNzLr?editors=1010
  • 17. Make asynchronous code easy again getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d) { getMoreData(function(e) { // do something }); }); }); }); }) async function doGreatThing() { try { const firstData = await getData(); const secondData = await getMoreData(firstData); const thirdData = await getMoreDate(secondData); // How about parallel call? const saveResults = await Promise.all([ saveData(firstData), saveData(secondData), saveData(thirdData)]); } catch (error) { console.log(error); } }
  • 18. Magic time, oops… demo time ● Sequential: https://codepen.io/huyhoangpham/pen/VMaYxe?editors=1010 ● Parellel: https://codepen.io/huyhoangpham/pen/JrXdXK?editors=1010 ● Looping: https://codepen.io/huyhoangpham/pen/rGeaXX?editors=1010
  • 19. Everything look … synchronous ● Await keyword is only available in a async function ● No more callback, then, or catch => Cleaner code ● Easier to debug ● Easy looping and error try/catch => Everything look … synchronous
  • 20. How about old browsers? ● Use babel transpiler ● Behind the scene: ● Generate a state machine
  • 21. Looking back We have came a long way ● From Callback to Promise(ES6) to Async/Await(ES7) ● Callback is still used for event, but should not for asynchronous call ● Should have a good understanding on Promise ● Use async/await if possible. It makes our life better JS Code Combo 1. Use bluebird to turn callback into promise 2. Use the magic of async/await
  • 22. Thank you for listening!