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

はじめよう async/await

Hirofumi Horiuchi
June 27, 2019
38

はじめよう async/await

Hirofumi Horiuchi

June 27, 2019
Tweet

Transcript

  1. “ 実装例 (async / await) async function getDataAsync() { const

    result = await getData(); console.log(result); }
  2. “ 実装例 (Promise) function promisefunc() { sleep1Sec().then(() => { return

    sleep1Sec(); }).then(() => { return sleep1Sec(); }).then(() => { return sleep1Sec(); }).then(() => { return sleep1Sec(); }).then(() => { console.log('complete'); }); }
  3. “ 実装例 (async / await) async function asyncfunc() { await

    sleep1Sec(); await sleep1Sec(); await sleep1Sec(); await sleep1Sec(); await sleep1Sec(); console.log('complete'); }
  4. “ 実装例 (return) async function getData() { return 'test'; }

    getData().then(result => { console.log(result); }); 出力 test 文字列をreturn すると Promise<string> が返却される
  5. “ 実装例 (throw) async function getData() { throw new Error();

    } getData().catch((e) => { console.log('Error'); }); 出力 Error throw すると呼び出し元で catch できる
  6. “ 実装例 (正常系) async function getData() { return 'test'; }

    async function getAsyncData() { const result = await getData(); console.log(result); } 出力 test Promiseが返ってくるまで待つ。 resultにはresolve()で渡した値が 設定される。
  7. “ 実装例 (異常系) async function getData() { throw new Error();

    } async function getDataAsync() { await getData().catch(() => { console.log('Error1'); }); try { await getData(); } catch (e) { console.log('Error2'); } } .catch() が使える try - catch も使える
  8. await を忘れる 実行結果 async function getData() { await sleep1Sec() return

    'test'; } async function getAsyncData() { const result = getData(); console.log(result); } Promise{ <pending> } async function の中に await を書かないと 非同期にならない。
  9. 結果の比較 async function isSuccess() { await sleep1Sec(); return false; }

    async function getAsyncData() { if (await !isSuccess()) { console.log('fail'); } else { console.log('success'); } } If (await !asyncFunc()) と書いてしまう
  10. 結果の比較 if (await isSuccess() === false) { 結果 success 正しい書き方

    === or !== 等を利用して比較してあげればOK。 または、一度変数として取得してから比較する。
  11. forEach() の内部で async を使う async function consoleNumber(num) { await sleep1Sec();

    console.log(num); } async function consoleArray() { const array = [1, 2, 3]; array.forEach(async num => { await consoleNumber(num); }); console.log('complete'); }
  12. forEach() の内部で async を使う for (num of array) { await

    consoleNumber(num); } 結果 complete 1 2 3 正しい書き方 forEach ではなく、 for - of を利用する。 Array.prototype.forEach メソッドは async functionではなく、 callback に await がついていないから。