蓝色天空网mbsky.com · 知识 · 实践 · 创造Node.js · 本地阅读预览
教程 / 后端开发 / Node.js

Node.js async/await

核对 async 函数 Promise 自动包装、await 暂停语义、try/catch 与 Promise.catch 错误处理、Promise.all 并发优化及 ESM 顶层 await。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

async/await 运行机制与基本语法

`async/await` 是建立在 Promise 之上的语法糖,通过 `async` 标记异步函数、用 `await` 等待 Promise 解决或拒绝,使异步流程兼具同步阅读体验与清晰错误语义,彻底摆脱深层回调嵌套。

底层仍依托单线程事件循环调度:异步操作交由底层运行时接口处理(浏览器环境为 Web APIs,在 Node.js 中则由 libuv 与内置 C++ 异步接口承接),完成后将回调推入任务/微任务队列,事件循环在调用栈清空后依次恢复执行,因而不会阻塞主线程。

任何函数加上 `async` 关键字后都会恒定返回 Promise,即使函数体直接返回普通字符串也会被自动包装为已解决的 Promise;`await` 在函数体内暂停当前 `async` 函数直至目标 Promise 落定并返回结果。本站 Node.js v24.22.3 实测验证 `greet() instanceof Promise` 为 `true` 且解包得到 `'Hello Node'`。

错误处理与典型业务编排模式

异常既可在 `async` 函数内部用 `try/catch` 捕获并按需包装重抛,也可由调用方直接对返回的 Promise 链式调用 `.then().catch()` 处理。实测 `loadResource(false)` 在 `try/catch` 中重抛 `wrapped:RESOURCE_UNAVAILABLE`,随后被调用侧 `.catch()` 准确拦截。

实际业务中常区分两类编排:当多项请求彼此独立时,应先发起任务再用 `await Promise.all(...)` 并行等待,而非在循环里逐个 `await` 串行阻塞。实测 3 项异步任务循环串行时峰值并发 `maxConcurrent=1`,改用 `Promise.all` 后峰值并发达到 `3` 且输出顺序一致为 `['data:u1', 'data:u2', 'data:u3']`。而存在先后依赖的数据库查询(先按 `userId` 查用户再查帖子)则顺序 `await` 并由 `try/catch` 统一兜底,实测命中用户返回 `{ ok: true, user: 'Lin', postCount: 2 }`、缺失用户返回 `USER_NOT_FOUND:999`。

最佳实践与常见问题排查

编写 `async/await` 代码应坚持五项实践:始终用 `try/catch` 或 `.catch()` 处理潜在拒绝;函数尾部若仅直接透传 Promise 且不需在当前 `try` 内捕获异常时可省略多余 `await`;独立异步任务优先 `Promise.all` 并行化;控制嵌套深度并适度抽离辅助函数;留意循环体内的 `await` 对总延迟的影响。

三个高频问题需明确:其一,`async/await` 本质是 Promise 语法糖,任意 `async` 函数返回 Promise、`await` 可等待任意 Promise 或 thenable;其二,若 `async` 函数意外返回 `undefined`,往往是因为在 `await` 语句前遗漏了 `return`(实测 `missingReturnIsUndefined: true`,补上 `return` 后返回 `'computed_value'`);其三,顶层 `await` 在 ES 模块(`.mjs` 或 `package.json` 声明 `"type": "module"`)中原生可用(本实验脚本顶层实测直接解析 `{ moduleMode: 'esm', topLevelAwait: true, value: 42 }`),而在 CommonJS 模块中仍须包裹在 `async` 函数内。

实测 async 返回包装、遗漏 return 陷阱、串行与 Promise.all 并发差异及 ESM 顶层 await

javascript · 阅读源码
function deepEqual(a, b) {
  return JSON.stringify(a) === JSON.stringify(b);
}

// Genuine Top-Level Await in ESM (.mjs)
const topLevelResult = await Promise.resolve({ moduleMode: 'esm', topLevelAwait: true, value: 42 });

// Case 1: async function always wraps return value in Promise + missing return pitfall
async function greet() {
  return 'Hello Node';
}

async function missingReturnPitfall() {
  await Promise.resolve('computed_value');
}

async function properReturn() {
  return await Promise.resolve('computed_value');
}

const greetPromise = greet();
const actual1 = {
  isPromise: greetPromise instanceof Promise,
  greetValue: await greetPromise,
  missingReturnResult: await missingReturnPitfall(),
  properReturnResult: await properReturn(),
};
const expected1 = {
  isPromise: true,
  greetValue: 'Hello Node',
  missingReturnResult: undefined,
  properReturnResult: 'computed_value',
};
// JSON.stringify drops undefined keys, so normalize explicitly
actual1.missingReturnIsUndefined = actual1.missingReturnResult === undefined;
delete actual1.missingReturnResult;
expected1.missingReturnIsUndefined = true;
delete expected1.missingReturnResult;

// Case 2: Error handling via try/catch (with rethrow) and caller .then/.catch
async function loadResource(ok) {
  try {
    if (!ok) {
      await Promise.reject(new Error('RESOURCE_UNAVAILABLE'));
    }
    return { status: 200, data: 'ok' };
  } catch (err) {
    throw new Error(`wrapped:${err.message}`);
  }
}

const okRes = await loadResource(true);
const caughtByCaller = await loadResource(false)
  .then(() => 'unreachable')
  .catch((err) => err.message);

const actual2 = { okRes, caughtByCaller };
const expected2 = {
  okRes: { status: 200, data: 'ok' },
  caughtByCaller: 'wrapped:RESOURCE_UNAVAILABLE',
};

// Case 3: Parallel Promise.all vs Sequential await in loop
async function measureConcurrency(mode) {
  let active = 0;
  let maxConcurrent = 0;
  const items = ['u1', 'u2', 'u3'];

  async function fetchItem(id) {
    active += 1;
    if (active > maxConcurrent) maxConcurrent = active;
    await new Promise((r) => setTimeout(r, 15));
    active -= 1;
    return `data:${id}`;
  }

  let out;
  if (mode === 'sequential') {
    out = [];
    for (const id of items) {
      out.push(await fetchItem(id));
    }
  } else {
    out = await Promise.all(items.map((id) => fetchItem(id)));
  }
  return { maxConcurrent, out };
}

const seqStats = await measureConcurrency('sequential');
const parStats = await measureConcurrency('parallel');
const actual3 = { seqStats, parStats };
const expected3 = {
  seqStats: { maxConcurrent: 1, out: ['data:u1', 'data:u2', 'data:u3'] },
  parStats: { maxConcurrent: 3, out: ['data:u1', 'data:u2', 'data:u3'] },
};

// Case 4: Async database-style lookup pipeline
const usersTable = new Map([[101, { id: 101, name: 'Lin' }]]);
const postsTable = [
  { id: 1, userId: 101, title: 'Event Loop Notes' },
  { id: 2, userId: 101, title: 'Stream Pipeline' },
];

async function findUserById(userId) {
  await Promise.resolve();
  const user = usersTable.get(userId);
  if (!user) throw new Error(`USER_NOT_FOUND:${userId}`);
  return user;
}

async function findPostsByUser(userId) {
  await Promise.resolve();
  return postsTable.filter((p) => p.userId === userId);
}

async function getUserAndPosts(userId) {
  try {
    const user = await findUserById(userId);
    const posts = await findPostsByUser(user.id);
    return { ok: true, user: user.name, postCount: posts.length };
  } catch (err) {
    return { ok: false, error: err.message };
  }
}

const actual4 = {
  found: await getUserAndPosts(101),
  missing: await getUserAndPosts(999),
};
const expected4 = {
  found: { ok: true, user: 'Lin', postCount: 2 },
  missing: { ok: false, error: 'USER_NOT_FOUND:999' },
};

// Case 5: Top-level await in ESM verification
const actual5 = topLevelResult;
const expected5 = { moduleMode: 'esm', topLevelAwait: true, value: 42 };

const cases = [
  { name: 'async_return_wrapping_and_undefined_pitfall', passed: deepEqual(actual1, expected1), expected: expected1, actual: actual1 },
  { name: 'try_catch_and_promise_catch', passed: deepEqual(actual2, expected2), expected: expected2, actual: actual2 },
  { name: 'parallel_promise_all_vs_sequential', passed: deepEqual(actual3, expected3), expected: expected3, actual: actual3 },
  { name: 'async_service_pipeline', passed: deepEqual(actual4, expected4), expected: expected4, actual: actual4 },
  { name: 'top_level_await_in_esm', passed: deepEqual(actual5, expected5), expected: expected5, actual: actual5 },
];

console.log(JSON.stringify({ version: process.version, cases }));
预期结果 · 待实际运行核验
  • 核对 async 返回 Promise、遗漏 return 得到 undefined、try/catch 重抛与 caller .catch、并发度 1 vs 3 及 ESM 顶层 await 实测输出。
实测 async 返回包装、遗漏 return 陷阱、串行与 Promise.all 并发差异及 ESM 顶层 await

所需环境:Windows x64、Node.js v24.22.3 本地运行环境。

当前源码 SHA256:5867045bf5853e3b4f12bbe226604d29ef7e36d94b702b962f74a42bcf1db5d2

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Node.js async/await实验

所需环境:Windows x64、Node.js v24.22.3 本地运行环境。

ZIP SHA256:00cc6214a75ec6aac54307fdcd9a4533316ed75c2e7fa826fc10cd09af58dfdb

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在循环中对 3 个互不依赖的异步接口逐一使用 `await` 与使用 `await Promise.all(...)` 有何性能差别?在 CommonJS 文件中可以直接使用顶层 `await` 吗?

展开参考解答

循环内逐一 `await` 会将总耗时叠加为各请求之和(并发度为 1),`Promise.all` 会同时发出全部请求使总耗时接近最慢单个请求(并发度为 3);CommonJS 不支持顶层 `await`,需包裹在异步函数中或改用 ES 模块(`.mjs` / `"type": "module"`)。

规范与官方依据