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フル活用時代だからこそ学んでおきたい働き方の心得
shinoyu
0
130
例外処理とどう使い分ける?Result型を使ったエラー設計 #burikaigi
kajitack
16
6k
組織で育むオブザーバビリティ
ryota_hnk
0
170
AI時代の認知負荷との向き合い方
optfit
0
140
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
490
SourceGeneratorのススメ
htkym
0
190
Amazon Bedrockを活用したRAGの品質管理パイプライン構築
tosuri13
4
240
FOSDEM 2026: STUNMESH-go: Building P2P WireGuard Mesh Without Self-Hosted Infrastructure
tjjh89017
0
150
MUSUBIXとは
nahisaho
0
130
メルカリのリーダビリティチームが取り組む、AI時代のスケーラブルな品質文化
cloverrose
2
510
AI Agent Tool のためのバックエンドアーキテクチャを考える #encraft
izumin5210
6
1.8k
インターン生でもAuth0で認証基盤刷新が出来るのか
taku271
0
190
Featured
See All Featured
How To Speak Unicorn (iThemes Webinar)
marktimemedia
1
380
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
1
120
Fantastic passwords and where to find them - at NoRuKo
philnash
52
3.6k
Speed Design
sergeychernyshev
33
1.5k
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
0
3.4k
The Spectacular Lies of Maps
axbom
PRO
1
520
The Curious Case for Waylosing
cassininazir
0
230
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
2.7k
The State of eCommerce SEO: How to Win in Today's Products SERPs - #SEOweek
aleyda
2
9.5k
Collaborative Software Design: How to facilitate domain modelling decisions
baasie
0
130
The Success of Rails: Ensuring Growth for the Next 100 Years
eileencodes
47
7.9k
Thoughts on Productivity
jonyablonski
74
5k
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で簡単楽しい非同期処理