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
はじめよう async/await
Search
Hirofumi Horiuchi
June 27, 2019
0
46
はじめよう async/await
Hirofumi Horiuchi
June 27, 2019
Tweet
Share
More Decks by Hirofumi Horiuchi
See All by Hirofumi Horiuchi
Stimulusのはなし
h_reader
0
31
同じってなんだ?
h_reader
0
29
OSSを読んでみた?
h_reader
0
51
vue_js_composition_api
h_reader
0
62
秒速でリリースするWebアプリ.pdf
h_reader
0
37
Node.jsではじめるオレオレツールの世界
h_reader
0
450
Featured
See All Featured
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
226
22k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
6
550
Code Review Best Practice
trishagee
66
17k
Mobile First: as difficult as doing things right
swwweet
223
9.3k
The Cost Of JavaScript in 2023
addyosmani
47
7.3k
Raft: Consensus for Rubyists
vanstee
137
6.8k
Statistics for Hackers
jakevdp
797
220k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
27
1.5k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
132
33k
Embracing the Ebb and Flow
colly
84
4.6k
Speed Design
sergeychernyshev
26
790
Into the Great Unknown - MozCon
thekraken
35
1.6k
Transcript
はじめようasync/await
“ JSでの非同期処理に async / await 使ってますか?
“ バリバリ使ってるよって人?
“ 一生使うつもりのない人?
“ Promise を使っても構いませんが、 使ったことがない人に向けてasync/await を簡単に説明します
なぜ、async / await なのか 1
“ Promiseより コードが見やすくなるから
“ 実装例 (Promise) function getDataPromise() { getData().then(result => { console.log(result);
}); }
“ 実装例 (async / await) async function getDataAsync() { const
result = await getData(); console.log(result); }
“ 非同期処理がもっとたくさんある場合
“ 実装例 (Promise) function promisefunc() { sleep1Sec().then(() => { return
sleep1Sec(); }).then(() => { return sleep1Sec(); }).then(() => { return sleep1Sec(); }).then(() => { return sleep1Sec(); }).then(() => { console.log('complete'); }); }
“ 実装例 (async / await) async function asyncfunc() { await
sleep1Sec(); await sleep1Sec(); await sleep1Sec(); await sleep1Sec(); await sleep1Sec(); console.log('complete'); }
“ async/await の方が 見やすくないですか??
async methodの説明 2
“ asyncメソッド内では、 return -> resolve() throw -> reject()
“ 実装例 (return) async function getData() { return 'test'; }
getData().then(result => { console.log(result); }); 出力 test 文字列をreturn すると Promise<string> が返却される
“ 実装例 (throw) async function getData() { throw new Error();
} getData().catch((e) => { console.log('Error'); }); 出力 Error throw すると呼び出し元で catch できる
await の説明 3
“ await 演算子は、 async function によって Promise が 返却されるのを待機する
“ 実装例 (正常系) async function getData() { return 'test'; }
async function getAsyncData() { const result = await getData(); console.log(result); } 出力 test Promiseが返ってくるまで待つ。 resultにはresolve()で渡した値が 設定される。
“ 実装例 (異常系) async function getData() { throw new Error();
} async function getDataAsync() { await getData().catch(() => { console.log('Error1'); }); try { await getData(); } catch (e) { console.log('Error2'); } } .catch() が使える try - catch も使える
async/await でありがちなミス 使い方を間違えないためのTips 4
await を忘れる 実行結果 async function getData() { await sleep1Sec() return
'test'; } async function getAsyncData() { const result = getData(); console.log(result); } Promise{ <pending> } async function の中に await を書かないと 非同期にならない。
結果の比較 async function isSuccess() { await sleep1Sec(); return false; }
async function getAsyncData() { if (await !isSuccess()) { console.log('fail'); } else { console.log('success'); } } If (await !asyncFunc()) と書いてしまう
結果の比較 if (await isSuccess() === false) { 結果 success 正しい書き方
=== or !== 等を利用して比較してあげればOK。 または、一度変数として取得してから比較する。
forEach() の内部で async を使う async function consoleNumber(num) { await sleep1Sec();
console.log(num); } async function consoleArray() { const array = [1, 2, 3]; array.forEach(async num => { await consoleNumber(num); }); console.log('complete'); }
forEach() の内部で async を使う for (num of array) { await
consoleNumber(num); } 結果 complete 1 2 3 正しい書き方 forEach ではなく、 for - of を利用する。 Array.prototype.forEach メソッドは async functionではなく、 callback に await がついていないから。
まとめ
“ よくあるミスさえ気をつければ、 async/await は Promiseよりも 見やすい快適なコードを 提供してくれます。 ぜひ、async/await を使いましょう!
“ ご清聴ありがとうございました。