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
47
はじめよう async/await
Hirofumi Horiuchi
June 27, 2019
Tweet
Share
More Decks by Hirofumi Horiuchi
See All by Hirofumi Horiuchi
Stimulusのはなし
h_reader
0
33
同じってなんだ?
h_reader
0
33
OSSを読んでみた?
h_reader
0
52
vue_js_composition_api
h_reader
0
66
秒速でリリースするWebアプリ.pdf
h_reader
0
41
Node.jsではじめるオレオレツールの世界
h_reader
0
480
Featured
See All Featured
The Pragmatic Product Professional
lauravandoore
36
7k
The Cost Of JavaScript in 2023
addyosmani
55
9k
StorybookのUI Testing Handbookを読んだ
zakiyama
31
6.2k
Leading Effective Engineering Teams in the AI Era
addyosmani
7
540
The World Runs on Bad Software
bkeepers
PRO
72
11k
No one is an island. Learnings from fostering a developers community.
thoeni
21
3.5k
GitHub's CSS Performance
jonrohan
1032
470k
Understanding Cognitive Biases in Performance Measurement
bluesmoon
31
2.7k
Testing 201, or: Great Expectations
jmmastey
45
7.7k
A better future with KSS
kneath
239
18k
Reflections from 52 weeks, 52 projects
jeffersonlam
353
21k
Fireside Chat
paigeccino
40
3.7k
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 を使いましょう!
“ ご清聴ありがとうございました。