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
38
はじめよう async/await
Hirofumi Horiuchi
June 27, 2019
Tweet
Share
More Decks by Hirofumi Horiuchi
See All by Hirofumi Horiuchi
Stimulusのはなし
h_reader
0
29
同じってなんだ?
h_reader
0
26
OSSを読んでみた?
h_reader
0
48
vue_js_composition_api
h_reader
0
57
秒速でリリースするWebアプリ.pdf
h_reader
0
20
Node.jsではじめるオレオレツールの世界
h_reader
0
390
Featured
See All Featured
Building Adaptive Systems
keathley
32
1.9k
Principles of Awesome APIs and How to Build Them.
keavy
121
16k
Building an army of robots
kneath
300
41k
[RailsConf 2023] Rails as a piece of cake
palkan
28
4k
Designing the Hi-DPI Web
ddemaree
276
33k
Raft: Consensus for Rubyists
vanstee
133
6.3k
ParisWeb 2013: Learning to Love: Crash Course in Emotional UX Design
dotmariusz
104
6.7k
Designing Experiences People Love
moore
136
23k
GraphQLの誤解/rethinking-graphql
sonatard
56
9.3k
The Illustrated Children's Guide to Kubernetes
chrisshort
32
47k
RailsConf & Balkan Ruby 2019: The Past, Present, and Future of Rails at GitHub
eileencodes
126
32k
Web development in the modern age
philhawksworth
203
10k
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 を使いましょう!
“ ご清聴ありがとうございました。