Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
JS Promise the right way
Search
Nguyễn Nhật Hoàng
October 29, 2016
Technology
240
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
JS Promise the right way
Ruby Meetup Ho Chi Minh City, 29th Oct 2016
Nguyễn Nhật Hoàng
October 29, 2016
More Decks by Nguyễn Nhật Hoàng
See All by Nguyễn Nhật Hoàng
Awesome React
codeaholicguy
0
390
Other Decks in Technology
See All in Technology
AI時代の「技術的負債」の変質ー概念の終焉と再解釈、エージェントと共に向かう先
nwiizo
0
2k
Slack上でインフラをトラブルシュートする! Agentic Platform Engineeringの第一歩
teru0x1
4
1.6k
例外の正しい扱い方 そのエラー try-catchして大丈夫?
jinwatanabe
3
500
安心して変更できるWebフロントエンドの作り方
pirosikick
4
2.2k
10分で知る最近のOmarchy
komagata
0
310
ユーザー価値を届け続けるためにウォンテッドリーが大切にしている文化
kotaminato
0
150
研究開発部の紹介 / Sansan R&D Profile
sansan33
PRO
5
25k
2026/09/10 Spring Bootから Jakarta EE/MicroProfileへの移行
megascus
0
360
GoにおけるFFIのこれまでとこれから
goccy
5
3k
synctest時代のhttptest Go 1.27で変わるHTTPサーバテストの裏側 / go conference2026 synctest and httptest
budougumi0617
1
2.9k
日経電子版を支えていく Kasane Design System/fec_fukuoka
nikkei_engineer_recruiting
0
1.4k
Minecraft JavaのMODをSwiftで作る
1mash0
0
160
Featured
See All Featured
SEO in 2025: How to Prepare for the Future of Search
ipullrank
3
3.8k
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
560
More Than Pixels: Becoming A User Experience Designer
marktimemedia
3
520
B2B Lead Gen: Tactics, Traps & Triumph
marketingsoph
0
240
Product Roadmaps are Hard
iamctodd
55
13k
Self-Hosted WebAssembly Runtime for Runtime-Neutral Checkpoint/Restore in Edge–Cloud Continuum
chikuwait
0
790
The untapped power of vector embeddings
frankvandijk
2
1.9k
Speed Design
sergeychernyshev
33
2.1k
New Earth Scene 8
popppiees
3
2.6k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
2.2k
Designing for humans not robots
tammielis
254
26k
Building the Perfect Custom Keyboard
takai
2
870
Transcript
JS PROMISE THE RIGHT WAY @codeaholicguy
CALLBACKS A piece of executable code that is passed as
an argument to other code, which is expected to call back (execute) the argument at some convenient time.
JQUERY CALLBACK STYLE $(document).ready(function() { $('#button').on('click', function(event) { $.getJSON('/data.json', function(data)
{ console.log(data); }); }); });
NODE.JS CALLBACK STYLE doSomething(params, function(error, result) { if (error) {
console.error(error.message); } else { console.log(result); } });
CALLBACK HELL getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d) {
getMoreData(function(e) { / / do something }); }); }); }); });
CALLBACK HELL getData(function(error, a) { if (error) { handleError(error); }
else { getMoreData(function(error, b) { if (error) { handleError(error); } else { getMoreData(function(error, c) { / / ... }); } }); } });
None
SO, WE DON'T WANT TO BLOCK BUT… > Callback functions
tend to become difficult to maintain and debug when nested within long lines of code. > Anonymous inline function in a callback can make reading the call stack very tedious.
PROMISE (ES6) > A promise represents the eventual result of
an asynchronous operation. > A promise must be in one of three states: pending, fulfilled, or rejected.
PROMISE (ES6) const promise = new Promise((resolve, reject) => {
/ / do async stuff resolve('DONE!'); }); promise.then((result) => { console.log(result); / / result will be 'DONE!' });
PROMISE (ES6) const promise = new Promise((resolve, reject) => {
/ / do async stuff reject(new Error('FAIL!')); }); promise .then((result) => { / / does not get called }) .catch((error) => { / / this does! });
PROMISE (ES6) function sleepAndReturn(duration, value) { return new Promise((resolve, reject)
=> { setTimeout(() => (resolve(value)), duration) }); } sleepAndReturn(1000, 'done') .then((result) => { console.log(result); / / result now equals 'done' })
PROMISE CHAINING sleepAndReturn(1000, 'done') .then((result1) => { return `${result1} ah
hihi` }) .then((result2) => { console.log(result2); / / result2 now equals 'done ah hihi' });
PROMISE CHAINING sleepAndReturn(1000, 'done') .then((result1) => { return sleepAndReturn(1000, `${result1}
ah hihi`) }) .then((result2) => { console.log(result2); / / result2 now equals 'done ah hihi' });
PROMISE CHAINING sleepAndReturn(1000, 'done') .then((result) => { throw new Error('Ops...');
}) .then((result1) => { / / do something }) .then((result2) => { / / do one more thing }) .catch((error) => { handleError(error); });
FROM THIS … getData(function(a) { getMoreData(function(b) { getMoreData(function(c) { getMoreData(function(d)
{ getMoreData(function(e) { / / do something }); }); }); }); });
TO THIS! getData() .then(getMoreData) .then(getMoreData) .then(getMoreData) .then(getMoreData) .then((result) => {
/ / do something }) .catch((error) => { handleError(error); });
PROMISE IS GOOD BECAUSE … > It is easier to
read as in cleaner method signatures. > It allows us to attach more than one callback to a single promise. > It allows for chaining of promises.
COMMON MISTAKES > One traditional example of using promises is
promise.then(resolve, reject); > Exception in success handler goes unnoticed.
COMMON MISTAKES > Test case at https:/ /github.com/codeaholicguy/promise-misses-error
BUT! > It is still quite cumbersome to handle even
simple logic. Don't you believe? Just thinking about making a for-loop with promises…
BLUEBIRD HELPERS Promise.any Promise.map Promise.reduce Promise.filter Promise.each
BUT IT IS STILL 3RD LIBRARY … > See you
next time with Generator & async/await (ES7) THANKS FOR LISTENING! > GITHUB @codeaholicguy > FACEBOOK @codeaholicguy