LoginSignup
0
0

More than 3 years have passed since last update.

async, await のシンプルな書き方メモ

Posted at

以前 Promiseのシンプルな書き方メモ というのを書きましたが、それのasync, await版です。


// 非同期処理taskA
const taskA = async (v) => {
  console.log('taskA', v);
  return await mainProc(v);
};

// 非同期処理taskB
const taskB = async (v) => {
  console.log('taskB', v);
  // return await mainProc(v);
  return await mainProcError();
};

// 非同期処理taskC
const taskC = async (v) => {
  console.log('taskC', v);
  return await mainProc(v);
}

// メイン処理
const mainProc = (v) => v + 1;

// メインエラー処理
const mainProcError = () => {
  throw new Error('error');
}

// エラーキャッチ時の処理
const onCatch = (e) => {
  console.log("catch", e);
  return "hoge";
};

// -----------
// メイン処理
// -----------
const main = async () => {
  let res = 1;
  res = await taskA(res);
  res = await taskB(res).catch(onCatch);
  res = await taskC(res);
  console.log("main", res);
};

main();

実行結果

taslA 1
taskB 2
catch Error: error
    at mainProcError (・・・略)
taskC hoge
main hoge1

動きをみて分かったこと

  • promise.then().then(). ・・・async内 await,await・・・で置き換えれる
  • await 内のエラーは .catch() で拾える
    • その際、catch内の関数 onCatch で return した値が awaitの返り値になる
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0