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
0
220
JS Promise the right way
Ruby Meetup Ho Chi Minh City, 29th Oct 2016
Nguyễn Nhật Hoàng
October 29, 2016
Tweet
Share
More Decks by Nguyễn Nhật Hoàng
See All by Nguyễn Nhật Hoàng
Awesome React
codeaholicguy
0
360
Other Decks in Technology
See All in Technology
生成AIの変革の時代に、直近1年で直面した課題とその解決策
ktc_wada
1
790
競技としてのKaggle、役に立つKaggle
yu4u
7
2.5k
kcp: Kubernetes APIs Are All You Need #techfeed_live / TechFeed Experts Night 28th
ytaka23
1
160
CockroachDB はどのくらい「しぶとい」のか? / How tough is CockroachDB?
kota2and3kan
6
3.9k
IaCジェネレーターとBedrockで詳細設計書を生成してみた
tsukasa_ishimaru
4
950
Amplify 🩷 Bedrock 〜生成AI入門〜
minorun365
PRO
10
1.1k
AWS アーキテクチャ作図入門/aws-architecture-diagram-101
ma2shita
16
6.5k
類似ロジック実装をiOS/Android間で合わせる道標No.1
fumiyasac0921
1
170
TDD - Test Driven Drupal
opdavies
0
3k
Building a RAG-poweredAI chat appwith Python and VS Code
pamelafox
0
180
Zero Data Loss Autonomous Recovery Service サービス概要
oracle4engineer
PRO
0
1.9k
中年男性がメインフレームから クラウドへキャリアシフトしてみた
uechishingo
1
430
Featured
See All Featured
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
123
39k
Agile that works and the tools we love
rasmusluckow
325
20k
How GitHub Uses GitHub to Build GitHub
holman
468
290k
The Power of CSS Pseudo Elements
geoffreycrofte
62
5k
Thoughts on Productivity
jonyablonski
60
3.9k
[RailsConf 2023] Rails as a piece of cake
palkan
28
4k
The Cost Of JavaScript in 2023
addyosmani
21
3.9k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
188
16k
Put a Button on it: Removing Barriers to Going Fast.
kastner
58
3.1k
Keith and Marios Guide to Fast Websites
keithpitt
408
22k
Unsuck your backbone
ammeep
664
57k
Clear Off the Table
cherdarchuk
85
310k
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