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
JavaScript Async Await
Search
Kazunari Sasa
August 09, 2019
Programming
0
67
JavaScript Async Await
Kazunari Sasa
August 09, 2019
Tweet
Share
Other Decks in Programming
See All in Programming
AIエージェントのキホンから学ぶ「エージェンティックコーディング」実践入門
masahiro_nishimi
3
300
Patterns of Patterns
denyspoltorak
0
1.4k
そのAIレビュー、レビューしてますか? / Are you reviewing those AI reviews?
rkaga
6
4.5k
CSC307 Lecture 02
javiergs
PRO
1
770
AI巻き込み型コードレビューのススメ
nealle
0
110
Rust 製のコードエディタ “Zed” を使ってみた
nearme_tech
PRO
0
140
16年目のピクシブ百科事典を支える最新の技術基盤 / The Modern Tech Stack Powering Pixiv Encyclopedia in its 16th Year
ahuglajbclajep
5
990
AIで開発はどれくらい加速したのか?AIエージェントによるコード生成を、現場の評価と研究開発の評価の両面からdeep diveしてみる
daisuketakeda
1
970
humanlayerのブログから学ぶ、良いCLAUDE.mdの書き方
tsukamoto1783
0
180
開発者から情シスまで - 多様なユーザー層に届けるAPI提供戦略 / Postman API Night Okinawa 2026 Winter
tasshi
0
190
Oxlint JS plugins
kazupon
1
650
AI時代の認知負荷との向き合い方
optfit
0
140
Featured
See All Featured
Fireside Chat
paigeccino
41
3.8k
Statistics for Hackers
jakevdp
799
230k
Ruling the World: When Life Gets Gamed
codingconduct
0
140
Navigating Algorithm Shifts & AI Overviews - #SMXNext
aleyda
0
1.1k
Odyssey Design
rkendrick25
PRO
1
490
The Impact of AI in SEO - AI Overviews June 2024 Edition
aleyda
5
730
How to Align SEO within the Product Triangle To Get Buy-In & Support - #RIMC
aleyda
1
1.4k
Performance Is Good for Brains [We Love Speed 2024]
tammyeverts
12
1.4k
sira's awesome portfolio website redesign presentation
elsirapls
0
140
The B2B funnel & how to create a winning content strategy
katarinadahlin
PRO
0
270
Navigating the Design Leadership Dip - Product Design Week Design Leaders+ Conference 2024
apolaine
0
170
Beyond borders and beyond the search box: How to win the global "messy middle" with AI-driven SEO
davidcarrasco
1
49
Transcript
簡単非同期 async await インターン 笹 和成
非同期処理とは
重い処理をバックグラウンドで動かすこと ストレージへのアクセス、サーバとの通信、 SQLの発行... ・普通の計算処理に比べて何倍も遅い。 ・遅いデータを待っている間、全てが動かなくなったら困る ・重い処理はバックグラウンドで動かそう
JavaScriptの非同期処理 ajax(‘hoge.com’, (res) => { // resを使った処理 }) ajax(‘hoge.com’) .then((response)
=> { // res を使った処理 }) callback関数 Promise 本日のテーマ: async await
callback地獄 (~ 2015) ajax(‘//hoge.com/data’, (response) => { getDataFromDisk(response.path, (imageData) =>
{ try { convertImage(imageData, (newImageData) => { ajax(‘//hoge.com/post’, newImageData, (response) => { appendToDOM(response.image); } ); }) } catch (e) { console.error(‘ エラーデス’, e) } }) })
Promise ( 2015 ~ ) ajax(‘//hoge.com/data’) .then((response) => { return
getDataFromDisk(response.path) }) .catch(e => throw e) .then((imageData) => { return convertImage(imageData) }) .then((newImageData) => { return ajax(‘//hoge.com/post’, newImageData) }) .then((response) => { appendToDOM(response.image); }) .catch((e) => { console.log(‘エラーデス’, e); });
async / await ( 2017 ~ ) const response =
await ajax(‘//hoge.com/data’); const imageData = await getDataFromDisk(response.path); try { const newImageData = await convertImage(newImageData); const { image } = await ajax(‘//hoge.com/post’) appendToDOM(image); } catch (e) { console.log(‘エラーデス’, e); }
今すぐ使えるasync await
await 演算子は async関数の中でしか使えない async function someFunction() { // 処理 }
class SomeClass { async someMethod() { // 処理 } } Function Class Method const someFunction = async () => { // 処理 } Arrow Function `async`を付ければasync関数になる
async関数は必ずPromiseを返す const asyncFunc = async () => { return ‘hello’;
} console.log(someFunc()); // => Promise{<pending>} asyncFunc() .then(console.log); // => ‘hello’ const callFunc = async () => { const str = await asyncFunc(); console.log(str) // => ‘hello’ }
return すると resolve, throw すると reject const asyncFunc = async
(bool) => { if (!bool) throw new Error(‘エラーデス’) return ‘Hello World’ } asyncFunc(true) .then(console.log) // => ‘Hello World’ asyncFunc(false) .then(console.log) // => Error: ‘エラーデス’ asyncFunc(false) .catch(_ => console.log(‘catch だよ’)) // => ‘catchだよ’ async関数 -> Promise
Tips & 使いどき
Tips: Promiseのメソッドと同時に使える const asyncFunction = async () => { const
json = await fetch(‘/getJson’) .then(r => r.json()); // .thenを使った方が良い場合もある (Fetch API等) const res = await fetch(‘/getJson’) const json = await res.json(); const data = await throwable() .catch(e => { console.error(‘ エラーデス’, e); }) // .catchを使えばtry-catchで囲む必要がなくなる try { const data = await throwable(); } catch (e) { console.error(‘ エラーデス’, e); } }
Tips: 並列実行も簡単 const asyncFunction = async () => { const
goodAjax = ajax(‘/good’); const greatAjax = ajax(‘/great’); const poorAjax = ajax(‘/poor’); const results = await Promise.all( [goodAjax, greatAjax, poorAjax] ) console.log(results); // => [ /goodのデータ, /greatのデータ, /poorのデータ ] } 一度に実行すれば効率が良い!
使いどき: 一つの関数に複数の非同期がある時
使いどき: 処理量の多い関数の時 const initialFetch = async () => { const
data = await fetchData(); longFunction(data); soLongFunction(data); // … /// expensiveFunction(data); } ネストは{長く, 深く}なるほど悪 一関数 一インデントを目指したい
# まとめ ・async awaitはPromiseをスッキリ書ける ・await演算子はresolveの内容を取得する ・async関数はPromiseを返却する ・async awaitで簡単楽しい非同期処理