.await是包装.then(onFulfilled)(成功回调)和错误抛出的语法糖
.catch是.then(null, onRejected)的语法糖
// 假设 fetchUser 和 fetchPosts 同样返回 Promise
async function getUserAndPosts(id) {
try {
const user = await fetchUser(id); // 等待 fetchUser Promise 解决
console.log("用户:", user.name);
const posts = await fetchPosts(user.id); // 等待 fetchPosts Promise 解决
console.log("帖子:", posts);
} catch (error) {
console.error("发生错误:", error);
} finally {
console.log("操作完成");
}
}
getUserAndPosts(123);老版本处理
then、catch、finally
// 假设 fetchUser 和 fetchPosts 都返回 Promise
function fetchUser(id) {
return new Promise(resolve => setTimeout(() => resolve({ id, name: "哲予" }), 500));
}
function fetchPosts(userId) {
return new Promise(resolve => setTimeout(() => resolve([`Post 1 for ${userId}`, `Post 2 for ${userId}`]), 700));
}
fetchUser(123)
.then(user => {
console.log("用户:", user.name);
return fetchPosts(user.id); // 返回一个新的 Promise
})
.then(posts => {
console.log("帖子:", posts);
})
.catch(error => {
console.error("发生错误:", error);
})
.finally(() => {
console.log("操作完成");
});