Node.js async/await
async/await 是 ES2017 引入的异步语法,基于 Promise 实现,使异步代码更易读。
async 函数
JavaScript
// async 函数返回 Promise
async function hello() {
return 'Hello';
}
hello().then(result => console.log(result));
// Hello
// 等价于
function hello() {
return Promise.resolve('Hello');
}
await 表达式
JavaScript
// await 等待 Promise 完成
async function fetchData() {
const result = await new Promise(resolve => {
setTimeout(() => resolve('数据'), 1000);
});
console.log(result); // 等待 1 秒后输出 '数据'
}
基本用法
JavaScript
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
return data;
} catch (err) {
console.error('读取失败:', err.message);
throw err;
}
}
readFile();
顺序执行
JavaScript
// 按顺序等待每个异步操作
async function processFiles() {
const file1 = await readFile('file1.txt');
const file2 = await readFile('file2.txt');
const file3 = await readFile('file3.txt');
console.log(file1, file2, file3);
// 依次读取,总耗时 = file1 + file2 + file3
}
并行执行
JavaScript
// 同时启动多个 Promise
async function processFilesParallel() {
const [file1, file2, file3] = await Promise.all([
readFile('file1.txt'),
readFile('file2.txt'),
readFile('file3.txt')
]);
console.log(file1, file2, file3);
// 并行读取,总耗时 = max(file1, file2, file3)
}
错误处理
JavaScript
async function handleData() {
try {
const data = await fetchData();
const processed = await processData(data);
return processed;
} catch (err) {
console.error('错误:', err.message);
// 可以选择恢复或重新抛出
throw err;
}
}
// 调用时处理错误
handleData().catch(err => console.error('外部捕获:', err));
返回值处理
JavaScript
async function getData() {
return 'data';
}
// async 函数返回 Promise
const result = getData();
console.log(result); // Promise { 'data' }
// 获取结果需要 await 或 then
async function main() {
const data = await getData();
console.log(data);
}
在类中使用
JavaScript
class UserService {
async getUser(id) {
const response = await fetch(`/api/users/${id}`);
return response.json();
}
async saveUser(user) {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify(user)
});
return response.json();
}
}
const service = new UserService();
const user = await service.getUser(1);
与 Promise 对比
JavaScript
// Promise 风格
function fetchUser() {
return fetch('/api/user')
.then(res => res.json())
.then(data => processData(data))
.catch(err => handleError(err));
}
// async/await 风格
async function fetchUser() {
try {
const res = await fetch('/api/user');
const data = await res.json();
return processData(data);
} catch (err) {
handleError(err);
}
}
async/await 让异步代码更易读,但本质仍是 Promise,理解 Promise 是基础。
要点总结
- async 函数返回 Promise,await 等待 Promise 完成
- await 会暂停函数执行,不会阻塞主线程
- 使用 try-catch 处理 await 中的错误
- 并行操作用 Promise.all + await
- async/await 是 Promise 的语法糖
📝 发现内容有误?点击此处直接编辑