0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

なぜ async/await で Promise チェーン全体をまとめるのか?

Posted at

Promise チェーン (.then() x n) だけで書けるのに、あえて await でチェーン全体をまとめる理由を整理しました。

4つのメリットに分けられます。

No. メリット 内容
1 通常のスコープで使える変数になる 値の再利用が自由。Promiseのスコープを超える
2 追加処理が柔軟 ネスト不要で可読性が高い
3 try-catch 一括管理 エラーがまとめて捕捉できる
4 分岐・条件判定が自然 if/switch が使いやすい

1. コード比較

1-A. チェーンだけで書く

function fetchAndRender() {
  fetch(url)
    .then(r => r.json())
    .then(json => json.items)
    .then(items => render(items));
}

1-B. await でチェーン全体をまとめる

async function fetchAndRender() {
  const items = await fetch(url)
    .then(r => r.json())
    .then(json => json.items);
  render(items);
}

結果は同じ。違いはチェーン後の拡張性や可読性など。

2. メリット詳細

2-1. 普通の変数になる

const items = await fetch(url).then(...);
logAnalytics(items);
render(items);
  • .then() に閉じ込められない。
  • デバッグも簡単:console.log(items) がどこでも使える。
  • 非同期かどうかを意識せず、同期コードのように書ける。

2-2. 追加処理が柔軟に書ける

チェーン型

.then(items => {
  const active = items.filter(i => i.active);
  return process(active).then(() => {
    if (active.length > 10) {
      alert('多い!');
    }
  });
})

await 版

const active = items.filter(i => i.active);
await process(active);
if (active.length > 10) {
  alert('多い!');
}
  • ネスト解消 → 保守性が向上。
  • returnPromise を気にせず書ける。

2-3. try-catch でエラーを一括管理

チェーン型

fetch(url)
  .then(...)
  .catch(err => handle(err));
  • 例外発生箇所が深いと煩雑。
  • 局所 catch を複数書くことも。

await 版

try {
  const items = await fetch(url).then(...);
  render(items);
} catch (err) {
  handle(err);
}
  • finally も使いやすい。
  • 全体を見通して例外処理できる。

2-4. 分岐・条件判定が自然

await 版

if (!items.length) return notifyEmpty();
for (const item of items) {
  await renderRow(item);
}
  • iffor など制御構文が使いやすい。
  • コールバックの深いネストから脱出。

3. チェーンだけで済ませるかどうか?

状況 推奨 理由
ステップが 1〜2 段で完結 チェーン 短くシンプル
後続処理がほぼ無い チェーン await はやや冗長
UI 更新や複数分岐が必要 await 可読性・保守性が上がる
エラーをまとめて管理したい await try-catch が有効

4. まとめ

  • await でチェーンをまとめる最大の利点は、「結果を普通の変数として取り出せる」こと。
  • それにより、ネストの解消、エラーの集中管理、分岐の自由度が得られる。
  • 単純なケースは .then() の方が短く済む。
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?