Skip to content

Instantly share code, notes, and snippets.

@LeeDDHH
Created June 10, 2021 04:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeeDDHH/3c54aeb8466cc734e619a6535bf11c14 to your computer and use it in GitHub Desktop.
Save LeeDDHH/3c54aeb8466cc734e619a6535bf11c14 to your computer and use it in GitHub Desktop.
async-awaitの中のtry-catch地獄を回避するための方法

基本的な async-await の書き方

const asynchronousCode = async () => {
  const a = await step1();
  const b = await step2(a);
  const c = await step3(b);
  
  return a + b + c;
}

try-catch を含めた場合の async-await の書き方

const asynchronousCode = async () => {
  let a;
  let b;
  let c;

  try {
    a = await step1();
  } catch (error) {
    handle(error);
  }
  
  try {
    b = await step2(a);
  } catch (error) {
    handle(error);
  }
  
  try {
    c = await step3(b);
  } catch (error) {
    handle(error);
  }

  return a + b + c;
}
  • try-catch 文で、長くなる…

簡単にエラーをキャッチして処理を書く場合

const betterAsynchronousCode = async () => {
  const a = await step1().catch(err => handle(err));
  const b = await step2(a).catch(err => handle(err));
  const c = await step3(b).catch(err => handle(err));
  
  return a + b + c;
}

標準エラー処理(Standardize Error Handling)化した処理を書く場合

// 標準エラー処理化させたtry-catchの処理
// 正常に処理されたら、dataとnullを返す
// 例外処理されたら、nullとerrorを返す
const standadizedHandle = async () => {
  try {
    const data = await somePromise;
    return [data, null];
  } catch (error) {
    console.error(error);
    return [null, error];
  }
}

// 標準エラー処理を使うときの書き方
// 返り値を分割代入して、例外発生時の処理を追加する
const asynchronousCode = async () => {
  const [data, error] = await standadizedHandle();

  if (error) handle(error);
  
  const [data2, error2] = await standadizedHandle();

  if (error2) handle(error);

  const [data3, error3] = await standadizedHandle();
  
  if (error3) handle(error);
}

出典

Async Await try-catch hell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment