Skip to content

异步/等待 in 深度

编写 asynchronous code 那个读取顶部-到-底部使用异步函数 and 等待 keyword.

你将学到

  • Declaring 异步函数 and 什么它们返回
  • Awaiting Promise and pausing execution
  • 错误 handling 使用 try/catch 围绕等待
  • 运行 Promise in parallel 使用 Promise.所有
  • 顶部-level 等待 and 否-等待-in-循环 trade-off

概念讲解

Linear Async Code

异步/等待 (ES2017) is syntax built on top of promises. An 异步 function always returns a promise — if you return a value, it is wrapped in a promise; if you return a promise, it is passed through. Inside an async function, 等待 pauses execution until a promise settles, then yields its value. The result is asynchronous code that reads like synchronous code, top to bottom.

Error Handling

Because await throws when a promise rejects, you wrap await calls in try/catch — the same construct used for synchronous errors. This is a major readability win over .catch() chains, especially when multiple async steps can fail in different ways. A single try/catch can guard an entire sequence.

Sequential vs Parallel

A common mistake is awaiting independent calls one after another, which runs them sequentially and wastes time. If the calls do not depend on each other, start them all at once and await the combined result with Promise.所有. This turns N sequential round-trips into one parallel batch.

Awaiting in Loops

Using 等待 inside a for loop runs each iteration sequentially. This is correct when each iteration depends on the previous one, but slow for independent work. For independent items, use Promise.所有(项.映射(asyncFn)) to run them concurrently. Reserve sequential await-in-loop for genuinely dependent steps.

Top-Level Await

In ES modules (not CommonJS), you can use 等待 at the top level of a module without wrapping it in an async function. This simplifies module initialization that needs async setup. In non-module scripts and CommonJS, you still need an async wrapper or an IIFE.

Under the Hood

async/await does not replace promises — it desugars to promise chains. Every async function is a function returning a promise, and every await is a then call. Understanding promises is therefore essential to debug async/await code, especially around error handling and parallelism.

示例代码

              // An async function always returns a promise
async function fetchUser(id) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}

// try/catch for error handling — reads like sync code
async function getUserSafe(id) {
  try {
    const user = await fetchUser(id);
    return user;
  } catch (e) {
    console.error("Failed:", e.message);
    return null;
  }
}

// Sequential — each waits for the previous (slow!)
async function loadSequential() {
  const a = await fetchUser(1);
  const b = await fetchUser(2);
  return [a, b];
}

// Parallel — both start at once (fast!)
async function loadParallel() {
  const [a, b] = await Promise.all([fetchUser(1), fetchUser(2)]);
  return [a, b];
}

// Sequential await in a loop — correct for dependent steps
async function fetchChain(startId, steps) {
  let current = startId;
  for (let i = 0; i < steps; i++) {
    const user = await fetchUser(current);
    console.log("step", i, user?.name);
    current = user?.id + 1; // next depends on previous
  }
}

// Top-level await in an ES module
const users = await loadParallel();
console.log("loaded:", users.length);
            

Shows 异步获取使用错误 handling, sequential 对比 parallel 加载 (Promise.所有), sequential 等待 in 循环 for dependent steps, and 顶部-level 等待 in 模块.

动手试一试

常见错误

错误写法

Awaiting independent calls sequentially 相反的 in parallel

正确做法

如果 calls 做不 depend on 每个 other, use Promise.所有([fetchA(), fetchB()]) 到运行它们 concurrently. Sequential 等待 wastes 时间 waiting for 每个 one 之前开始下一个.

错误写法

Forgetting 那个异步函数返回 Promise, 不值 directly

正确做法

异步函数总是返回 Promise. 到获取值, caller 必须等待它 or use .然后(). 你 cannot 返回 plain 值从 异步函数到 synchronous caller.

相关速查表

查阅不认识的术语

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

查看术语表

动手做项目

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

查看项目

解读错误信息

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

查看错误