Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
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
DatadogのBits Chatが開発組織にもたらしたもの / What Bits Chat Has Brought Us
sms_tech
1
290
アクセスキーが漏れた日にやるべきこと- 無効化の先にある本当の対応
kazzpapa3
0
190
LLM Internals: 언어 모델의 계보와 알고리즘 진화 (2023~2026)
inureyes
PRO
1
870
AIペネトレーションテスト・ セキュリティ検証「AgenticSec」紹介資料
laysakura
2
9.4k
Head First モブプログラミング / Head First Mobprogramming
takaking22
10
12k
Go 1.27 の標準パッケージに uuid が入った!のでいろいろ喋る / go_127_std_go_uuid
convto
3
580
平文パスワードはログに“残り” ── 肝心の侵入は“痕跡すら残らない”
kuroneko13
0
120
同じWAFが、攻撃の“形”は弾く── 正当な“形”の不正は通す
kuroneko13
0
270
医療の現場を変革に挑戦した半年間の軌跡 - PythonとAIで現場を変える / From Code to Care
soudai
PRO
0
540
【GCC2026】TrueHDRIを用いたルックデブ環境とライティングテクニック
bandainamcostudios
PRO
0
220
自宅NWにISR4331を導入してみた話
okaits
0
120
暗号化?某ファイルストレージはどうなるの!? 3rd Partyとうまく付き合う秘密度ラベル設計
kasada
0
120
Featured
See All Featured
Ten Tips & Tricks for a 🌱 transition
stuffmc
0
170
Leading Effective Engineering Teams in the AI Era
addyosmani
9
2.4k
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
950
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
2
400
Automating Front-end Workflow
addyosmani
1369
210k
Designing Powerful Visuals for Engaging Learning
tmiket
1
500
How to audit for AI Accessibility on your Front & Back End
davetheseo
0
500
More Than Pixels: Becoming A User Experience Designer
marktimemedia
3
500
Mozcon NYC 2025: Stop Losing SEO Traffic
samtorres
1
490
Public Speaking Without Barfing On Your Shoes - THAT 2023
reverentgeek
1
540
Learning to Love Humans: Emotional Interface Design
aarron
275
41k
jQuery: Nuts, Bolts and Bling
dougneiner
66
8.5k
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