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
48
JavaScript Async Await
Kazunari Sasa
August 09, 2019
Tweet
Share
Other Decks in Programming
See All in Programming
Code Reviews
bkuhlmann
4
890
Apache Hive 4 on Treasure Data
ryukobayashi
0
200
Random\Randomizer クラスで日常のあれこれを解決しよう! / Random\Randomizer class solves familiar trouble
cocoeyes02
0
230
[技育CAMPアカデミア]アイディアを形に!【超入門】スマホアプリ開発〜リリースまでの流れをご紹介
teamlab
PRO
0
370
Rethinking UI building strategies @ SFI 2024
letelete
0
270
Rubyでたのしむクリエイティブコーディング/Enjoy Creative coding with Ruby
chobishiba
1
180
try!Swift Tokyo 2024 参加報告 LT
akidon0000
1
220
코틀린으로 멀티플랫폼 만들기
pangmoo
0
150
Build Apps for iOS, Android & Desktop in 100% Kotlin With Compose Multiplatform (mDevCamp 2024)
zsmb
0
320
Azure OpenAI Serviceのプロンプトエンジニアリング入門
tomokusaba
3
690
GraphQLサーバの構成要素を整理する #ハッカー鮨 #tsukijigraphql / graphql server technology selection
izumin5210
4
830
検証も兼ねて個人開発でHonoとかと向き合った話
hanetsuki
0
890
Featured
See All Featured
GitHub's CSS Performance
jonrohan
1025
450k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
244
20k
Atom: Resistance is Futile
akmur
259
25k
How to Ace a Technical Interview
jacobian
272
22k
How GitHub Uses GitHub to Build GitHub
holman
468
290k
JavaScript: Past, Present, and Future - NDC Porto 2020
reverentgeek
40
4.4k
Producing Creativity
orderedlist
PRO
337
39k
jQuery: Nuts, Bolts and Bling
dougneiner
59
7.1k
Agile that works and the tools we love
rasmusluckow
325
20k
Why You Should Never Use an ORM
jnunemaker
PRO
51
8.6k
The Cost Of JavaScript in 2023
addyosmani
16
3.9k
How To Stay Up To Date on Web Technology
chriscoyier
782
250k
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で簡単楽しい非同期処理