Async/Await 的基本概念
Async/Await 是 ECMAScript 2017(ES8)引入的语法糖,用于简化 Promise 的使用。async 关键字用于声明异步函数,await 用于等待 Promise 的解决(resolve)或拒绝(reject)。
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
错误处理机制
使用 try/catch 捕获异步操作中的错误,避免代码因未处理的 Promise 拒绝而中断。
async function fetchWithErrorHandling() {
try {
const response = await fetch('https://api.example.com/invalid-url');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Fetch failed:', error);
}
}
并行执行多个异步任务
通过 Promise.all 结合 Async/Await 实现并行任务,提升执行效率。
async function fetchMultipleUrls() {
const [userData, posts] = await Promise.all([
fetch('https://api.example.com/users/1').then(res => res.json()),
fetch('https://api.example.com/posts').then(res => res.json())
]);
console.log({ userData, posts });
}
Async/Await 与 Promise 的对比
Async/Await 更接近同步代码的写法,可读性更高。以下是 Promise 链与 Async/Await 的对比示例:
Promise 链写法:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
Async/Await 写法:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
实际应用示例:用户登录流程
模拟一个完整的用户登录流程,包括验证和数据处理。
async function login(username, password) {
const response = await fetch('https://api.example.com/login', {
method: 'POST',
body: JSON.stringify({ username, password })
});
if (!response.ok) throw new Error('Login failed');
return await response.json();
}
async function getUserProfile(token) {
const response = await fetch('https://api.example.com/profile', {
headers: { Authorization: `Bearer ${token}` }
});
return await response.json();
}
async function handleLogin() {
try {
const { token } = await login('user123', 'password');
const profile = await getUserProfile(token);
console.log('User profile:', profile);
} catch (error) {
console.error('Login error:', error.message);
}
}
注意事项
-
避免在循环中误用
await:在循环中直接使用await会导致顺序执行,应改用Promise.all优化。// 错误示例(顺序执行) async processArray(array) { for (const item of array) { await processItem(item); // 效率低 } } // 正确示例(并行执行) async processArray(array) { await Promise.all(array.map(item => processItem(item))); } -
Top-Level Await:在 ES2022 中,模块顶层可直接使用
await,无需包裹在async函数中。const data = await fetchData(); // 仅在模块中支持 console.log(data);
通过以上示例和技巧,可以高效地利用 Async/Await 简化异步代码逻辑,提升开发体验。
835

被折叠的 条评论
为什么被折叠?



