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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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を使ったコードレビューで定性的に品質カバー
chiilog
1
260
Automatic Grammar Agreementと Markdown Extended Attributes について
kishikawakatsumi
0
180
15年続くIoTサービスのSREエンジニアが挑む分散トレーシング導入
melonps
2
190
AgentCoreとHuman in the Loop
har1101
5
230
IFSによる形状設計/デモシーンの魅力 @ 慶應大学SFC
gam0022
1
300
カスタマーサクセス業務を変革したヘルススコアの実現と学び
_hummer0724
0
680
ぼくの開発環境2026
yuzneri
0
190
Rust 製のコードエディタ “Zed” を使ってみた
nearme_tech
PRO
0
160
Data-Centric Kaggle
isax1015
2
770
AIエージェント、”どう作るか”で差は出るか? / AI Agents: Does the "How" Make a Difference?
rkaga
4
2k
humanlayerのブログから学ぶ、良いCLAUDE.mdの書き方
tsukamoto1783
0
190
AI時代のキャリアプラン「技術の引力」からの脱出と「問い」へのいざない / tech-gravity
minodriven
20
7.1k
Featured
See All Featured
Building a Modern Day E-commerce SEO Strategy
aleyda
45
8.6k
Cheating the UX When There Is Nothing More to Optimize - PixelPioneers
stephaniewalter
287
14k
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
0
140
How to train your dragon (web standard)
notwaldorf
97
6.5k
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
380
Breaking role norms: Why Content Design is so much more than writing copy - Taylor Woolridge
uxyall
0
160
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
31
3.1k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
200
Unsuck your backbone
ammeep
671
58k
Statistics for Hackers
jakevdp
799
230k
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.6k
A Modern Web Designer's Workflow
chriscoyier
698
190k
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で簡単楽しい非同期処理