async函数返回Promise,await可暂停异步函数等待Promise结果,用try...catch处理错误,Promise.all()实现并发,避免循环中滥用await。

async/await 是 JavaScript 中处理异步操作的一种更清晰、更简洁的语法,它基于 Promise 构建,让你可以用同步的方式写异步代码,避免回调地狱(callback hell)。
什么是 async 函数
async 关键字用于声明一个函数是异步的。只要在函数前加上 async,这个函数就会自动返回一个 Promise。
即使函数中没有显式返回 Promise,JavaScript 也会将其包装成已解决(resolved)的 Promise。
示例:
async function getData() {
return "Hello";
}
getData().then(data => console.log(data)); // 输出: Hello
await 的作用与用法
await 只能在 async 函数内部使用,它会暂停函数的执行,等待 Promise 完成后再继续。
使用 await 可以直接获取 Promise 的结果值,而不是通过 .then() 链式调用。
基本语法:
async function fetchData() {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}
上面代码中,fetch 返回一个 Promise,await 让我们像写同步代码一样等待结果。
错误处理:try...catch
由于 await 会等待 Promise,如果 Promise 被拒绝(rejected),就需要捕获异常。推荐使用 try...catch 结构。
示例:捕获网络请求错误
async function safeFetch() {
try {
const response = await fetch('https://api.example.com/bad-url');
if (!response.ok) throw new Error('请求失败');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('出错了:', error.message);
}
}
并发执行多个异步任务
如果你有多个不依赖彼此的异步操作,可以使用 Promise.all() 来并发执行,提升性能。
示例:并行请求
async function loadAllData() {
try {
const [res1, res2] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/posts').then(r => r.json())
]);
console.log(res1, res2);
} catch (error) {
console.error('加载失败:', error);
}
}
注意:Promise.all() 中任何一个 Promise 失败都会触发 catch,若需容错可考虑 Promise.allSettled()。
常见注意事项
- await 只能在 async 函数中使用,否则会报语法错误。
- 不要在循环中盲目使用 await,可能导致串行延迟,必要时先用 Promise.all() 包装。
- async 函数始终返回 Promise,调用时记得处理返回值(.then 或再 await)。
基本上就这些。掌握 async/await 后,你的异步代码会更易读、更易维护。不复杂但容易忽略细节,多练习就能熟练。










