2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Promise.allSettledでも全件成功とは限らない:結果・順序・同期例外の3点をNode.jsで実測

2
Posted at

Promise.allSettled() を待って catch に入らなくても、全件成功とは限りません。

入力の Promise が reject しても、全体は fulfilled になります。次の3点を点検します。

実測環境は macOS 27.2.1 / Node.js v24.22.1。2026年11月25日実行。通信・ブラウザ・Windows は未検証です。

1. catchだけで全件成功を判定していないか

try {
  const results = await Promise.allSettled([
    Promise.resolve("保存済み"),
    Promise.reject(new Error("保存失敗")),
  ]);
  console.log(results.map(r => r.status).join(","));
  for (const r of results) {
    if (r.status === "rejected") console.log(r.reason.message);
  }
} catch {
  console.log("全体のcatch");
}

出力:

fulfilled,rejected
保存失敗

全体のcatch は出ません。成功行は value、失敗行は reason を読みます。

「全件保存しました」と出すなら、rejected の有無も調べます。

2. 結果配列を完了順だと思っていないか

const completed = [];
let finishFirst;
const first = new Promise(resolve => { finishFirst = resolve; });
const second = Promise.resolve("B").then(value => {
  completed.push(value);
  finishFirst("A");
  return value;
});
const results = await Promise.allSettled([
  first.then(value => { completed.push(value); return value; }),
  second,
]);
console.log("完了:", completed.join(","));
console.log("結果:", results.map(r => r.value).join(","));

出力:

完了: B,A
結果: A,B

B→A の完了でも結果は入力順です。

送信時の ID 配列を保持し、待機中の並べ替えで結果との対応を崩さないようにします。

3. 同期例外がallSettledに渡る前に起きていないか

const run = name => {
  if (name === "bad") throw new Error("引数エラー");
  return Promise.resolve(name);
};
try {
  const results = await Promise.allSettled(["ok", "bad"].map(run));
  console.log(results.length);
} catch (error) {
  console.log("外側:", error.message);
}

const results = await Promise.allSettled(
  ["ok", "bad"].map(name => Promise.resolve().then(() => run(name))),
);
console.log(results.map(r => r.status).join(","));

出力:

外側: 引数エラー
fulfilled,rejected

前半は map(run) で例外が投げられ、allSettled に到達しません。後半は then 内の例外が rejection になります。

後半は全件を開始する設計です。不備があれば全処理を止めたい場合は、開始前に検証します。同時実行数の制限や自動再試行は含みません。

AIに頼む確認

「各行の status」「ID の対応」「同期例外の扱い」を指定し、全件成功・一部成功・開始前の失敗を確認します。

仕様:Promise.allSettled。


未経験者向けの体験版を公開しています

※ 中上級者には易しすぎる内容なので、初心者の知り合いへの紹介や社内研修の参考としてどうぞ。

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?