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
65
秒速でリリースするWebアプリ.pdf
h_reader
0
41
Node.jsではじめるオレオレツールの世界
h_reader
0
480
Featured
See All Featured
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
8
530
The Straight Up "How To Draw Better" Workshop
denniskardys
236
140k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.5k
Building Applications with DynamoDB
mza
96
6.6k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
50k
A better future with KSS
kneath
239
17k
Why You Should Never Use an ORM
jnunemaker
PRO
59
9.5k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
61k
Designing for Performance
lara
610
69k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
Agile that works and the tools we love
rasmusluckow
330
21k
Speed Design
sergeychernyshev
32
1.1k
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 を使いましょう!
“ ご清聴ありがとうございました。