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
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
就職⽀援サービスにおけるキャリアアドバイザーのシフトスケジューリング
recruitengineers
PRO
1
150
アンオフィシャルな、オフィシャルからのお願い
wyamazak_devrel
0
120
AIエージェントが名古屋の猛暑からあなたを守る
happysamurai294
0
130
Kubernetesにおける学習基盤とLLMOpsの概要
ry
1
310
気軽に使える"情報のハブ"としてのNotion活用 〜フロー情報の集積点 と、 Claude Code × Notion AI〜
syucream
1
150
【Snowflake Summit 2026 Recap!!】Snowflake Summit Deep Dive: Security & Governance
civitaspo
1
240
LLMにもCAP定理があるという話
harukasakihara
0
390
AIっぽい文章を採点して人間らしく直すアプリを作ってみた
yama3133
2
200
連合学習と機密コンピューティング
lycorptech_jp
PRO
0
120
【NRUG vol.18】なぜ多くのオブザーバビリティ導入は失敗するのか
nrug_member
0
170
ルールやカスタム機能、どう活かす?ハンズオンで体感するIBM Bobの出力コントロール
muehara
1
170
Snowflakeと仲良くなる第一歩
coco_se
4
490
Featured
See All Featured
技術選定の審美眼(2025年版) / Understanding the Spiral of Technologies 2025 edition
twada
PRO
118
120k
Jamie Indigo - Trashchat’s Guide to Black Boxes: Technical SEO Tactics for LLMs
techseoconnect
PRO
0
170
Noah Learner - AI + Me: how we built a GSC Bulk Export data pipeline
techseoconnect
PRO
0
200
Prompt Engineering for Job Search
mfonobong
0
350
Mind Mapping
helmedeiros
PRO
1
250
Producing Creativity
orderedlist
PRO
348
40k
The Director’s Chair: Orchestrating AI for Truly Effective Learning
tmiket
1
190
Bridging the Design Gap: How Collaborative Modelling removes blockers to flow between stakeholders and teams @FastFlow conf
baasie
0
590
Stop Working from a Prison Cell
hatefulcrawdad
274
21k
Building AI with AI
inesmontani
PRO
1
1.1k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
Docker and Python
trallard
47
3.9k
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