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
32
同じってなんだ?
h_reader
0
32
OSSを読んでみた?
h_reader
0
51
vue_js_composition_api
h_reader
0
64
秒速でリリースするWebアプリ.pdf
h_reader
0
39
Node.jsではじめるオレオレツールの世界
h_reader
0
470
Featured
See All Featured
Speed Design
sergeychernyshev
32
1k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
667
120k
Adopting Sorbet at Scale
ufuk
77
9.4k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
34
3.1k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
8
800
Six Lessons from altMBA
skipperchong
28
3.9k
Let's Do A Bunch of Simple Stuff to Make Websites Faster
chriscoyier
507
140k
The Invisible Side of Design
smashingmag
300
51k
BBQ
matthewcrist
89
9.7k
Easily Structure & Communicate Ideas using Wireframe
afnizarnur
194
16k
How STYLIGHT went responsive
nonsquared
100
5.6k
Writing Fast Ruby
sferik
628
62k
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 を使いましょう!
“ ご清聴ありがとうございました。