Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript Async Await

JavaScript Async Await

Kazunari Sasa

August 09, 2019
Tweet

Other Decks in Programming

Transcript

  1. JavaScriptの非同期処理 ajax(‘hoge.com’, (res) => { // resを使った処理 }) ajax(‘hoge.com’) .then((response)

    => { // res を使った処理 }) callback関数 Promise 本日のテーマ: async await
  2. 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) } }) })
  3. 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); });
  4. 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); }
  5. await 演算子は async関数の中でしか使えない async function someFunction() { // 処理 }

    class SomeClass { async someMethod() { // 処理 } } Function Class Method const someFunction = async () => { // 処理 } Arrow Function `async`を付ければasync関数になる
  6. 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’ }
  7. 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
  8. 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); } }
  9. 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のデータ ] } 一度に実行すれば効率が良い!
  10. 使いどき: 処理量の多い関数の時 const initialFetch = async () => { const

    data = await fetchData(); longFunction(data); soLongFunction(data); // … /// expensiveFunction(data); } ネストは{長く, 深く}なるほど悪 一関数 一インデントを目指したい