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 heregreet().then(console.log); // HelloAwait
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()链式调用。 - 错误统一在一个地方处理。
对比
| Promise | Async/Await |
|---|---|
task → then → then → catch | task → await → result (线性流程) |
何时使用 async/await
- 与 API 打交道时
- 处理多个异步操作时
- 想要干净、可读的代码
async/await 是现代 JavaScript 中最重要的特性之一。它帮助你:
编写更简洁的异步代码
避免回调地狱
优雅地处理错误
async→ 返回一个 Promiseawait→ 等待一个 Promise
比 Promise 更简洁,错误处理使用 try...catch。