JavaScript 中的 Async/Await:编写更简洁的异步代码

发布: (2026年4月4日 GMT+8 13:45)
3 分钟阅读
原文: Dev.to

Source: Dev.to

回调函数(难以阅读)

setTimeout(() => {
  setTimeout(() => {
    console.log("Step 3");
  }, 1000);
}, 1000);
  • 难以阅读
  • 难以维护

Promise(比回调好,但仍然冗长)

fetchData()
  .then(data => {
    return processData(data);
  })
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.error(err);
  });
  • 比回调好一些
  • 仍然需要链式 .then()

引入 async/await 的目的在于:

  • 简化异步代码
  • 提高可读性
  • 避免链式 .then()

它是对 Promise 的语法糖。

Async 函数

async 函数始终返回一个 Promise。

// Example placeholder – add your async function here
greet().then(console.log); // Hello

Await

await 关键字会暂停执行,直到 Promise 解决。

// Example placeholder – use await inside an async function

👉 它让异步代码看起来像同步代码。


Async 函数执行流程

async function starts

await pauses execution

promise resolves

execution resumes
// You can add a comparison diagram or code here if needed

使用 Async/Await

async function run() {
  try {
    const data = await fetchData();
    const result = await processData(data);
    console.log(result);
  } catch (err) {
    console.error(err);
  }
}
  • 更加简洁、易读
  • 使用 try...catch 处理错误
// Additional error‑handling examples can be placed here

重要注意事项

  • await 只能在 async 函数内部使用。
  • 它会暂停执行 但不会阻塞整个程序
  • 必须使用 try...catch 来捕获错误。

实际案例

async function fetchUser() {
  try {
    const response = await fetch("https://api.example.com/user");
    const data = await response.json();

    console.log(data);
  } catch (err) {
    console.error("Failed to fetch user");
  }
}
  • 看起来像同步代码——没有 .then() 链式调用。
  • 错误统一在一个地方处理。

对比

PromiseAsync/Await
task → then → then → catchtask → await → result (线性流程)

何时使用 async/await

  • 与 API 打交道时
  • 处理多个异步操作时
  • 想要干净、可读的代码

async/await 是现代 JavaScript 中最重要的特性之一。它帮助你:

  • 编写更简洁的异步代码

  • 避免回调地狱

  • 优雅地处理错误

  • async → 返回一个 Promise

  • await → 等待一个 Promise

比 Promise 更简洁,错误处理使用 try...catch

0 浏览
Back to Blog

相关文章

阅读更多 »

执行上下文

想象 Execution Context 像一个厨房。在你开始烹饪(执行代码)之前,你需要工作空间、变量工具和函数配方。