async/await 是现代 JavaScript 中处理异步操作的革命性特性,
它基于 Promise 构建,让异步代码拥有同步代码的可读性和简洁性。
async/await 异步编程详解
核心概念
1. async 函数
声明一个异步函数,自动返回 Promise 对象
函数内部可以使用 await 关键字
语法:async function functionName() { … }
async function fetchData() {
return "Data fetched";
}
// 等同于
function fetchData() {
return Promise.resolve("Data fetched");
}
2. await 表达式
只能在 async 函数内部使用
暂停 async 函数执行,等待 Promise 解决
返回 Promise 的解决值
语法:const result = await promise;
async function getUser() {
const response = await fetch('/api/user'); // 等待fetch完成
const user = await response.json(); // 等待JSON解析
return user;
}
执行机制详解
1. 事件循环中的 await
当遇到 await 时:
暂停 async 函数执行
将函数剩余部分放入微任务队列
继续执行事件循环中的其他任务
当 Promise 解决后,恢复 async 函数执行
console.log("Start");
async function example() {
console.log("Before await");
await new Promise(res => setTimeout(res, 1000));
console.log("After await");
}
example();
console.log("End");
/* 输出顺序:
Start
Before await
End
(1秒后)
After await
*/
2. 错误处理机制
async/await 使用 try/catch 处理错误,类似同步代码:
async function fetchWithRetry(url, retries = 3) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP error: ${
response.status}`);
return await response.json();
} catch (error) {
if (retries > 0) {
console.log(`Retrying... (${
retries} left)`);
await new Promise(res => setTimeout(res, 1000))