Skip to content

Promise in 深度

Promise 状态, chaining, 错误 propagation, and combinators 如 Promise.所有 and Promise.race.

你将学到

  • three Promise 状态: pending, fulfilled, 拒绝
  • Chaining 使用然后 and transforming 值
  • 错误 propagation and catch 跨越链
  • Combinators: Promise.所有, Promise.race, Promise.allSettled, Promise.任何
  • 创建 Promise 从 scratch 使用 executor 函数

概念讲解

Promise States

promise 是一种object representing a future result。 It is always in one of three states: pending (the operation has not finished), fulfilled (it succeeded with a value), or rejected (it failed with a reason). Once a promise settles (fulfills or rejects), it is immutable — it will never change state again. This is what makes promises safer than callbacks, which can be called multiple times by mistake.

Chaining with then

.然后(onFulfilled, onRejected) returns a new promise that resolves with whatever the handler returns. This lets you chain transformations: each 然后 takes the previous value and produces the next. If a handler returns a promise, the chain waits for it to settle before continuing — this is how you sequence async steps without nesting.

Error Propagation

A rejected promise skips forward to the next catch (or the onRejected handler). Errors propagate down the chain like exceptions in a try/catch. A single catch at the end can handle errors from any step above. 最后() runs regardless of outcome and is useful for cleanup, but it does not receive the value or reason.

Combinators

Promise.所有 waits for all promises and rejects if any one rejects — use it for parallel work where all must succeed. Promise.allSettled waits for all and never rejects; it gives you an array of {status, value/reason} results — ideal when you want partial success. Promise.race settles with the first promise to settle (fulfill or reject). Promise.任何 (ES2021) fulfills with the first to fulfill, ignoring rejections unless all reject.

The Executor

You create a promise with 新 Promise((resolve, 拒绝) => { ... }). The executor runs synchronously and calls resolve(值) or 拒绝(reason) when the work is done. Call resolve/reject exactly once — subsequent calls are ignored. Throw inside the executor to reject automatically.

示例代码

              // Creating a promise from scratch
function delay(ms, value) {
  return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}

// Chaining: each then transforms the value
delay(100, 10)
  .then((n) => n * 2)        // 20
  .then((n) => n + 5)        // 25
  .then((n) => console.log("chained:", n));

// Error propagation across a chain
function risky(x) {
  return new Promise((resolve, reject) => {
    if (x < 0) reject(new Error("negative input"));
    else resolve(Math.sqrt(x));
  });
}
risky(-1)
  .then((r) => console.log("root:", r))
  .catch((e) => console.log("caught:", e.message)) // "negative input"
  .finally(() => console.log("done"));

// Promise.all — parallel, all must succeed
async function loadAll() {
  const [a, b, c] = await Promise.all([
    delay(100, "A"),
    delay(150, "B"),
    delay(50, "C"),
  ]);
  console.log("all:", a, b, c); // waits ~150ms
}
loadAll();

// Promise.allSettled — partial success, never rejects
async function loadBestEffort() {
  const results = await Promise.allSettled([
    delay(100, "ok"),
    Promise.reject(new Error("fail")),
  ]);
  results.forEach((r) =>
    console.log(r.status, r.value ?? r.reason?.message)
  );
}
loadBestEffort();
            

Shows 创建 Promise 使用 executor, chaining transformations, 错误 propagation 使用 catch and 最后, Promise.所有 for parallel 成功, and Promise.allSettled for 部分-成功 handling.

动手试一试

常见错误

错误写法

创建 Promise 链那个 swallows 错误因为 catch 是 missing

正确做法

Unhandled rejections 能 crash 节点.js or log 警告 in 浏览器. 总是端 链使用 .catch() or use 异步/等待使用 try/catch. In 节点, listen for 处理.on('unhandledRejection').

错误写法

Using Promise.所有当 一些请求可能 legitimately 失败

正确做法

Promise.所有拒绝如果任何单个 Promise 拒绝, losing successful results. Use Promise.allSettled 到获取每个 result 使用状态字段, 然后筛选 or handle failures individually.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误