异步编程
Promise
// Promise基础
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success');
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
// Promise链式调用
fetchUserData()
.then(user => fetchUserPosts(user.id))
.then(posts => processPosts(posts))
.catch(error => handleError(error));
Async/Await
// 基本使用
async function getData() {
try {
const user = await fetchUser();
const posts = await fetchUserPosts(user.id);
return posts;
} catch (error) {
console.error(error);
}
}
// 并行处理
async function getMultipleData() {
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts()
]);
return { users, posts };
}
异步迭代
// for await...of
async function* asyncGenerator() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
}
async function processItems() {
for await (const item of asyncGenerator()) {
console.log(item);
}
}
错误处理
- Promise错误处理
- try/catch使用
- 全局错误处理
- 异步错误传播