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
250
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
Transcript
23 slides
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
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
技術書典で本を売る流れ
yoshimura_datam
0
130
共通基盤の実装に Kotlin - Quarkus を選定した理由と採用したアーキテクチャ
nealle
1
160
Web Performance Is a Journey [PerfNow 2026]
tammyeverts
2
150
おうち環境でも「なるべく止めたくない!」 ― おうち環境の機器冗長化の理想と現実
yuutosi
1
700
OpenTelemetryで変わった 新時代のCloudWatchメトリクス監視
tsukuboshi
0
500
20261119_AgentCore
takuyay0ne
2
270
新規事業開発でのAWS活用成功談&失敗談! 〜新規事業開発を専門に行うRelicならではのAWS活用〜
amixedcolor
1
140
AIエージェントのアーキテクチャ設計
nsatoh
0
540
【Oracle AI SPOTLIGHT ウェビナー】AI時代、狙われるデータと止められない業務をどう守るか?
oracle4engineer
PRO
1
140
お風呂場をサーバルームにしよう
yusuke427
0
400
Welcome JXL!
dynamis
0
120
プラガブルで宣言的なソフトウェアファクトリーを支えるTypeScript
timakin
2
570
Featured
See All Featured
Odyssey Design
rkendrick25
PRO
3
970
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
17k
Save Time (by Creating Custom Rails Generators)
garrettdimon
PRO
33
5.9k
The agentic SEO stack - context over prompts
schlessera
0
1k
Typedesign – Prime Four
hannesfritz
42
3.2k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
18k
Code Reviewing Like a Champion
maltzj
529
40k
Practical Orchestrator
shlominoach
192
12k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
35
2.6k
Game over? The fight for quality and originality in the time of robots
wayneb77
1
340
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
2
410
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
3
3.9k