SlideShare a Scribd company logo
Async/Await Revisited
We will talk about callback,
promise and async/await.
Hi, I’m Riza
JavaScript is
asyncrhonous
JS waits for nobody
JS will move on without
waiting some process to finish.
Async Example
• Ajax call
• Access user's webcam
• Resize image
How we deal with it?
Good Old Callback
“Callbacks are func!ons that
you pass as arguments to be
invoked when the callee has
finished its job.”
Callback is...
Eric Elliot
getProfile("rizafahmi", (err, profile) 
=> {
getRepos(profile.login, (err, repos) 
=> {
countTotalStars(repos, (err, stars) 
=> {

// count the stars
});
});
});
getProfile("rizafahmi", (err, profile) 
=> {
getRepos(profile.login, (err, repos) 
=> {
countTotalStars(repos, (err, stars) 
=> {

// count the stars
});
});
});
getProfile("rizafahmi", (err, profile) 
=> {
getRepos(profile.login, (err, repos) 
=> {
countTotalStars(repos, (err, stars) 
=> {

// count the stars
});
});
});
const handleCountStars = (err, stars) 
=> {
console.log(`Total stars: ${stars}`);
};
const handleRepos = (err, repos) 
=> {
countTotalStars(repos, handleCountStars);
};
const handleProfile = (err, profile) 
=> {
getRepos(profile.login, handleRepos);
};
getProfile("rizafahmi", handleProfile);
const handleCountStars = (err, stars) 
=> {
console.log(`Total stars: ${stars}`);
};
const handleRepos = (err, repos) 
=> {
countTotalStars(repos, handleCountStars);
};
const handleProfile = (err, profile) 
=> {
getRepos(profile.login, handleRepos);
};
getProfile("rizafahmi", handleProfile);
const handleCountStars = (err, stars) 
=> {
console.log(`Total stars: ${stars}`);
};
const handleRepos = (err, repos) 
=> {
countTotalStars(repos, handleCountStars);
};
const handleProfile = (err, profile) 
=> {
getRepos(profile.login, handleRepos);
};
getProfile("rizafahmi", handleProfile);
const handleCountStars = (err, stars) 
=> {
console.log(`Total stars: ${stars}`);
};
const handleRepos = (err, repos) 
=> {
countTotalStars(repos, handleCountStars);
};
const handleProfile = (err, profile) 
=> {
getRepos(profile.login, handleRepos);
};
getProfile("rizafahmi", handleProfile);
Great! But it's hard to read/
write
THE Promise
Promise is...
“A Promise is a proxy for a value not
necessarily known when the promise
is created. It allows you to
associate handlers with an
asynchronous action's eventual
success value or failure reason.”
Mozilla Develpoer Network
Promise is...
A promise is an object that may produce
a single value some time in the future:
either a resolved value, or a reason that
it’s not resolved.
Eric Elliot
getProfile("rizafahmi")
.then(profile 
=> {
return getRepos(profile.login)})
.then(repos 
=> {
return countTotalStars(repos)})
.catch(err 
=> {
console.error(err) })
getProfile("rizafahmi")
.then(profile 
=> {
return getRepos(profile.login)})
.then(repos 
=> {
return countTotalStars(repos)})
.catch(err 
=> {
console.error(err) })
getProfile("rizafahmi")
.then(profile 
=> {
return getRepos(profile.login)})
.then(repos 
=> {
return countTotalStars(repos)})
.catch(err 
=> {
console.error(err) })
getProfile("rizafahmi")
.then(profile 
=> getRepos(profile.login))
.then(repos 
=> countTotalStars(repos))
.catch(err 
=> {
console.error(err);
});
BUUUUUTTTTTT.....
$riza_profile = get_profile("rizafahmi");
$riza_repos = get_repos($riza_profile[“login"]);
$riza_stars = count_total_stars($riza_repos);
riza_profile = get_profile("rizafahmi")
riza_repos = get_repos(riza_profile[“login"])
riza_stars = count_total_stars(riza_repos)
Async/await
(async () 
=> {
const riza_profile = await getProfile("rizafahmi");
const riza_repos = await getRepos(riza_profile.login);
const riza_stars = countTotalStars(riza_repos);
})();
(async () 
=> {
const riza_profile = await getProfile("rizafahmi");
const riza_repos = await getRepos(riza_profile.login);
const riza_stars = countTotalStars(riza_repos);
})();
const countStars = async () 
=> {
const riza_profile = await getProfile("rizafahmi");
const riza_repos = await getRepos(riza_profile.login);
const riza_stars = countTotalStars(riza_repos);
};
countStars();
const countStars = async () 
=> {
const riza_profile = await getProfile("rizafahmi");
const riza_repos = await getRepos(riza_profile.login);
const riza_stars = countTotalStars(riza_repos);
};
countStars();
Buuuuuttttt....
Somebody said error handling in
async/await is ugly....
Option #1
Make sure errors don't happen
#problemsolved
Option #2
try/catch
(async () 
=> {
try {
const profile = await getProfile("rizafahmi");
const repos = await getRepos(profile.data.items[0].login);
const stars = countTotalStars(repos.data);
console.log(`Total stars: ${stars}`);
} catch (e) {
console.error(e);
}
})();
Option #3
Handle error when you call it
(async () 
=> {
const profile = await getProfile("rizafahmi").catch(e 
=> console.error(e));
const repos = await getRepos(profile.data.items[0].login).catch(e 
=>
console.error(e)
);
const stars = countTotalStars(repos.data);
console.log(`Total stars: ${stars}`);
})();
(async () 
=> {
const profile = await getProfile("rizafahmi").catch(e 
=> console.error(e));
const repos = await getRepos(profile.data.items[0].login).catch(e 
=>
console.error(e)
);
const stars = countTotalStars(repos.data);
console.log(`Total stars: ${stars}`);
})();
(async () 
=> {
const profile = await getProfile("rizafahmi").catch(e 
=> console.error(e));
const repos = await getRepos(profile.data.items[0].login).catch(e 
=>
console.error(e)
);
const stars = countTotalStars(repos.data);
console.log(`Total stars: ${stars}`);
})();
Option #4
Higher Order Func!ons
const handleError = fn 
=> {
return (

...params) 
=> {
return fn(

...params).catch(e 
=> {
console.error(e);
});
};
};
const safeGetProfile = handleError(getProfile);
(async () 
=> {
const riza = await safeGetProfile("rizafahmi");
console.log(riza.data.items[0].login);
})();
const handleError = fn 
=> {
return (

...params) 
=> {
return fn(

...params).catch(e 
=> {
console.error(e);
});
};
};
const safeGetProfile = handleError(getProfile);
(async () 
=> {
const riza = await safeGetProfile("rizafahmi");
console.log(riza.data.items[0].login);
})();
const handleError = fn 
=> {
return (

...params) 
=> {
return fn(

...params).catch(e 
=> {
console.error(e);
});
};
};
const safeGetProfile = handleError(getProfile);
(async () 
=> {
const riza = await safeGetProfile("rizafahmi");
console.log(riza.data.items[0].login);
})();
const safeGetProfile = handleError(getProfile);
(async () 
=> {
const riza = await safeGetProfile("rizafahmi");
console.log(riza.data.items[0].login);
})();
const handleError = fn 
=> (

...params) 
=> fn(

...params).catch(console.error(e));
“If just using callback you can solving
your problem, why you have push
your self using Promise?!”
Hengki Sihombing, CTO, Co-Founder Urbanhire
async/await Revisited
And I’m done!
github.com/rizafahmi/callback-promise-async-revisited
slideshare.net/rizafahmi
riza@hack!v8.com
ceritanyadeveloper.com

More Related Content

PDF
Essentials and Impactful Features of ES6
ODP
Introduccion a Jasmin
PDF
Deferred
PDF
JavaScript and the AST
PPTX
Crafting beautiful software
PDF
Debugging: Rules And Tools - PHPTek 11 Version
PDF
Teaching Your Machine To Find Fraudsters
PDF
Simulator customizing & testing for Xcode 9
Essentials and Impactful Features of ES6
Introduccion a Jasmin
Deferred
JavaScript and the AST
Crafting beautiful software
Debugging: Rules And Tools - PHPTek 11 Version
Teaching Your Machine To Find Fraudsters
Simulator customizing & testing for Xcode 9

What's hot (19)

PDF
스위프트를 여행하는 히치하이커를 위한 스타일 안내
PPTX
Electrify your code with PHP Generators
PDF
Ruby closures, how are they possible?
PDF
You code sucks, let's fix it
PDF
Dollar symbol
PDF
Models and Service Layers, Hemoglobin and Hobgoblins
PDF
PHP Object Injection Vulnerability in WordPress: an Analysis
PDF
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
PDF
Your code sucks, let's fix it
PDF
Javascript ES6 generators
PDF
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
PDF
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
PDF
Workshop 5: JavaScript testing
KEY
Object Calisthenics Applied to PHP
PDF
Practical JavaScript Programming - Session 1/8
PDF
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
PDF
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
PDF
Command Bus To Awesome Town
KEY
循環参照のはなし
스위프트를 여행하는 히치하이커를 위한 스타일 안내
Electrify your code with PHP Generators
Ruby closures, how are they possible?
You code sucks, let's fix it
Dollar symbol
Models and Service Layers, Hemoglobin and Hobgoblins
PHP Object Injection Vulnerability in WordPress: an Analysis
Security Meetup 22 октября. «Реверс-инжиниринг в Enterprise». Алексей Секрето...
Your code sucks, let's fix it
Javascript ES6 generators
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHPKonf
Letswift18 워크숍#1 스위프트 클린코드와 코드리뷰
Workshop 5: JavaScript testing
Object Calisthenics Applied to PHP
Practical JavaScript Programming - Session 1/8
Mirror, mirror on the wall: Building a new PHP reflection library (DPC 2016)
“Writing code that lasts” … or writing code you won’t hate tomorrow. - PHP Yo...
Command Bus To Awesome Town
循環参照のはなし
Ad

Similar to async/await Revisited (20)

PDF
Painless Persistence with Realm
PDF
Intro to Asynchronous Javascript
PDF
Jasmine BDD for Javascript
PPTX
Art of Javascript
PDF
JS Fest 2019 Node.js Antipatterns
PDF
Painless Persistence in a Disconnected World
PDF
ERRest
PDF
Play á la Rails
PDF
How to React Native
PDF
A Lifecycle Of Code Under Test by Robert Fornal
PPTX
Nantes Jug - Java 7
PDF
Sane Async Patterns
PDF
Great Developers Steal
PPT
JSConf: All You Can Leet
PPTX
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
ODP
Concurrency on the JVM
PPTX
Async Redux Actions With RxJS - React Rally 2016
PDF
Take Data Validation Seriously - Paul Milham, WildWorks
KEY
Node.js
PDF
Take Data Validation Seriously - Paul Milham, WildWorks
Painless Persistence with Realm
Intro to Asynchronous Javascript
Jasmine BDD for Javascript
Art of Javascript
JS Fest 2019 Node.js Antipatterns
Painless Persistence in a Disconnected World
ERRest
Play á la Rails
How to React Native
A Lifecycle Of Code Under Test by Robert Fornal
Nantes Jug - Java 7
Sane Async Patterns
Great Developers Steal
JSConf: All You Can Leet
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Concurrency on the JVM
Async Redux Actions With RxJS - React Rally 2016
Take Data Validation Seriously - Paul Milham, WildWorks
Node.js
Take Data Validation Seriously - Paul Milham, WildWorks
Ad

More from Riza Fahmi (20)

PDF
Membangun Aplikasi Web dengan Elixir dan Phoenix
PDF
Berbagai Pilihan Karir Developer
PDF
Web dan Progressive Web Apps di 2020
PDF
Remote Working/Learning
PDF
How to learn programming
PDF
Rapid App Development with AWS Amplify
PDF
Menguak Misteri Module Bundler
PDF
Beberapa Web API Menarik
PDF
MVP development from software developer perspective
PDF
Ekosistem JavaScript di Indonesia
PDF
Perkenalan ReasonML
PDF
How I Generate Idea
PDF
Strategi Presentasi Untuk Developer Workshop Slide
PDF
Lesson Learned from Prolific Developers
PDF
Clean Code JavaScript
PDF
The Future of AI
PDF
Chrome Dev Summit 2018 - Personal Take Aways
PDF
Modern Static Site with GatsbyJS
PDF
Introduction to ReasonML
PDF
Machine learning with py torch
Membangun Aplikasi Web dengan Elixir dan Phoenix
Berbagai Pilihan Karir Developer
Web dan Progressive Web Apps di 2020
Remote Working/Learning
How to learn programming
Rapid App Development with AWS Amplify
Menguak Misteri Module Bundler
Beberapa Web API Menarik
MVP development from software developer perspective
Ekosistem JavaScript di Indonesia
Perkenalan ReasonML
How I Generate Idea
Strategi Presentasi Untuk Developer Workshop Slide
Lesson Learned from Prolific Developers
Clean Code JavaScript
The Future of AI
Chrome Dev Summit 2018 - Personal Take Aways
Modern Static Site with GatsbyJS
Introduction to ReasonML
Machine learning with py torch

Recently uploaded (20)

PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Electronic commerce courselecture one. Pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Encapsulation theory and applications.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
cuic standard and advanced reporting.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Electronic commerce courselecture one. Pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Machine learning based COVID-19 study performance prediction
Encapsulation theory and applications.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
cuic standard and advanced reporting.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Dropbox Q2 2025 Financial Results & Investor Presentation
Review of recent advances in non-invasive hemoglobin estimation
Per capita expenditure prediction using model stacking based on satellite ima...
Chapter 3 Spatial Domain Image Processing.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Understanding_Digital_Forensics_Presentation.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf

async/await Revisited

  • 1. Async/Await Revisited We will talk about callback, promise and async/await.
  • 4. JS waits for nobody
  • 5. JS will move on without waiting some process to finish.
  • 6. Async Example • Ajax call • Access user's webcam • Resize image
  • 7. How we deal with it?
  • 9. “Callbacks are func!ons that you pass as arguments to be invoked when the callee has finished its job.” Callback is... Eric Elliot
  • 10. getProfile("rizafahmi", (err, profile) => { getRepos(profile.login, (err, repos) => { countTotalStars(repos, (err, stars) => { // count the stars }); }); });
  • 11. getProfile("rizafahmi", (err, profile) => { getRepos(profile.login, (err, repos) => { countTotalStars(repos, (err, stars) => { // count the stars }); }); });
  • 12. getProfile("rizafahmi", (err, profile) => { getRepos(profile.login, (err, repos) => { countTotalStars(repos, (err, stars) => { // count the stars }); }); });
  • 13. const handleCountStars = (err, stars) => { console.log(`Total stars: ${stars}`); }; const handleRepos = (err, repos) => { countTotalStars(repos, handleCountStars); }; const handleProfile = (err, profile) => { getRepos(profile.login, handleRepos); }; getProfile("rizafahmi", handleProfile);
  • 14. const handleCountStars = (err, stars) => { console.log(`Total stars: ${stars}`); }; const handleRepos = (err, repos) => { countTotalStars(repos, handleCountStars); }; const handleProfile = (err, profile) => { getRepos(profile.login, handleRepos); }; getProfile("rizafahmi", handleProfile);
  • 15. const handleCountStars = (err, stars) => { console.log(`Total stars: ${stars}`); }; const handleRepos = (err, repos) => { countTotalStars(repos, handleCountStars); }; const handleProfile = (err, profile) => { getRepos(profile.login, handleRepos); }; getProfile("rizafahmi", handleProfile);
  • 16. const handleCountStars = (err, stars) => { console.log(`Total stars: ${stars}`); }; const handleRepos = (err, repos) => { countTotalStars(repos, handleCountStars); }; const handleProfile = (err, profile) => { getRepos(profile.login, handleRepos); }; getProfile("rizafahmi", handleProfile);
  • 17. Great! But it's hard to read/ write
  • 19. Promise is... “A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.” Mozilla Develpoer Network
  • 20. Promise is... A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved. Eric Elliot
  • 21. getProfile("rizafahmi") .then(profile => { return getRepos(profile.login)}) .then(repos => { return countTotalStars(repos)}) .catch(err => { console.error(err) })
  • 22. getProfile("rizafahmi") .then(profile => { return getRepos(profile.login)}) .then(repos => { return countTotalStars(repos)}) .catch(err => { console.error(err) })
  • 23. getProfile("rizafahmi") .then(profile => { return getRepos(profile.login)}) .then(repos => { return countTotalStars(repos)}) .catch(err => { console.error(err) })
  • 24. getProfile("rizafahmi") .then(profile => getRepos(profile.login)) .then(repos => countTotalStars(repos)) .catch(err => { console.error(err); });
  • 26. $riza_profile = get_profile("rizafahmi"); $riza_repos = get_repos($riza_profile[“login"]); $riza_stars = count_total_stars($riza_repos);
  • 27. riza_profile = get_profile("rizafahmi") riza_repos = get_repos(riza_profile[“login"]) riza_stars = count_total_stars(riza_repos)
  • 29. (async () => { const riza_profile = await getProfile("rizafahmi"); const riza_repos = await getRepos(riza_profile.login); const riza_stars = countTotalStars(riza_repos); })();
  • 30. (async () => { const riza_profile = await getProfile("rizafahmi"); const riza_repos = await getRepos(riza_profile.login); const riza_stars = countTotalStars(riza_repos); })();
  • 31. const countStars = async () => { const riza_profile = await getProfile("rizafahmi"); const riza_repos = await getRepos(riza_profile.login); const riza_stars = countTotalStars(riza_repos); }; countStars();
  • 32. const countStars = async () => { const riza_profile = await getProfile("rizafahmi"); const riza_repos = await getRepos(riza_profile.login); const riza_stars = countTotalStars(riza_repos); }; countStars();
  • 33. Buuuuuttttt.... Somebody said error handling in async/await is ugly....
  • 34. Option #1 Make sure errors don't happen #problemsolved
  • 36. (async () => { try { const profile = await getProfile("rizafahmi"); const repos = await getRepos(profile.data.items[0].login); const stars = countTotalStars(repos.data); console.log(`Total stars: ${stars}`); } catch (e) { console.error(e); } })();
  • 37. Option #3 Handle error when you call it
  • 38. (async () => { const profile = await getProfile("rizafahmi").catch(e => console.error(e)); const repos = await getRepos(profile.data.items[0].login).catch(e => console.error(e) ); const stars = countTotalStars(repos.data); console.log(`Total stars: ${stars}`); })();
  • 39. (async () => { const profile = await getProfile("rizafahmi").catch(e => console.error(e)); const repos = await getRepos(profile.data.items[0].login).catch(e => console.error(e) ); const stars = countTotalStars(repos.data); console.log(`Total stars: ${stars}`); })();
  • 40. (async () => { const profile = await getProfile("rizafahmi").catch(e => console.error(e)); const repos = await getRepos(profile.data.items[0].login).catch(e => console.error(e) ); const stars = countTotalStars(repos.data); console.log(`Total stars: ${stars}`); })();
  • 42. const handleError = fn => { return ( ...params) => { return fn( ...params).catch(e => { console.error(e); }); }; }; const safeGetProfile = handleError(getProfile); (async () => { const riza = await safeGetProfile("rizafahmi"); console.log(riza.data.items[0].login); })();
  • 43. const handleError = fn => { return ( ...params) => { return fn( ...params).catch(e => { console.error(e); }); }; }; const safeGetProfile = handleError(getProfile); (async () => { const riza = await safeGetProfile("rizafahmi"); console.log(riza.data.items[0].login); })();
  • 44. const handleError = fn => { return ( ...params) => { return fn( ...params).catch(e => { console.error(e); }); }; }; const safeGetProfile = handleError(getProfile); (async () => { const riza = await safeGetProfile("rizafahmi"); console.log(riza.data.items[0].login); })();
  • 45. const safeGetProfile = handleError(getProfile); (async () => { const riza = await safeGetProfile("rizafahmi"); console.log(riza.data.items[0].login); })(); const handleError = fn => ( ...params) => fn( ...params).catch(console.error(e));
  • 46. “If just using callback you can solving your problem, why you have push your self using Promise?!” Hengki Sihombing, CTO, Co-Founder Urbanhire