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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Nguyễn Nhật Hoàng
October 29, 2016
Technology
230
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
380
Other Decks in Technology
See All in Technology
GitHub Copilot 最新アップデート – 「一歩先」の実践活用術
moulongzhang
4
1.3k
新しいUbuntu/GNOMEが使いたいからXからWaylandへ移行頑張ってるの巻 2026-06-20
nobutomurata
0
140
エンジニアリング戦略の作り方 / Crafting Engineering Strategy
iwashi86
21
7k
非エンジニアがClaudeと挑んだ「1ヶ月間プロダクト30本ノック」
askokc
0
610
Claude Codeをどのように キャッチアップしているか
oikon48
13
8.3k
Claude Code の Sandbox 機能を Anthropic Sandbox Runtime(srt) で試そう!/lets-play-anthropic-sandbox-runtime
tomoki10
1
620
2026TECHFRESH畢業分享會 - Lightning Talk - E起 See See : 電商推薦讀心術? 數據說了算
line_developers_tw
PRO
0
1.1k
【Snowflake Summit 2026 Recap!!】Snowflake Summit Deep Dive: Security & Governance
civitaspo
1
230
AGENTS.mdとSkillsで始めるAIエージェント活用
sonoda_mj
3
220
2026 TECHFRESH 畢業分享會 - 開發日常大解密!從領域驅動到企業級上線
line_developers_tw
PRO
0
1.1k
Oracle AI Database@Google Cloud:サービス概要のご紹介
oracle4engineer
PRO
6
1.5k
失敗を資産に変えるClaude Code
shinyasaita
0
690
Featured
See All Featured
[RailsConf 2023 Opening Keynote] The Magic of Rails
eileencodes
31
10k
Building Adaptive Systems
keathley
44
3.1k
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
1
1.3k
The Myth of the Modular Monolith - Day 2 Keynote - Rails World 2024
eileencodes
28
3.5k
Darren the Foodie - Storyboard
khoart
PRO
3
3.4k
It's Worth the Effort
3n
188
29k
Why Mistakes Are the Best Teachers: Turning Failure into a Pathway for Growth
auna
0
160
The Power of CSS Pseudo Elements
geoffreycrofte
82
6.3k
Documentation Writing (for coders)
carmenintech
77
5.4k
For a Future-Friendly Web
brad_frost
183
10k
Claude Code どこまでも/ Claude Code Everywhere
nwiizo
65
56k
Building AI with AI
inesmontani
PRO
1
1.1k
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