当你使用await时特别是还要执行很多的请求时try...catch是不是像个跟屁虫一直跟着你,下面这个代码是不是一看脑袋都头痛。一直try一直try、try真想以脚给他踹了。
async function loadPageData(userId) {
try {
const user = await fetchUser(userId);
console.log('用户名字:', user.name);
try {
const posts = await fetchPosts(user.id);
console.log('内容:', posts);
try {
const comments = await fetchCommentsForPosts(posts[0].id);
console.log('文章评论:', comments);
} catch (commentError) {
console.error('获取评论失败:', commentError);
}
} catch (postError) {
console.error('获取文章失败:', postError);
}
} catch (userError) {
console.error('获取用户失败:', userError);
}
}
其实可以使用to这个属性,下面是使用to来重构的代码
to的优势总结
- 代码更扁平、更清晰:消除了
try...catch
的嵌套,让核心逻辑处于顶层作用域。 - 减少样板代码:将错误处理逻辑封装在可复用的
to
函数中。 - 强制性的错误处理:解构赋值
const [error, data]
迫使开发者正视error
的存在,不容易遗漏错误处理。 - 关注点分离:通过卫语句将错误处理逻辑与成功逻辑分离开,代码更易于维护。
还可以配合 Promise.all
使用
这个模式在处理多个并发请求时同样表现出色。
async function loadDashboard(userId) {
const [
[userError, userData],
[settingsError, settingsData]
] = await Promise.all([
to(fetchUser(userId)),
to(fetchUserSettings(userId))
]);
if (userError) {
console.error('加载用户数据失败');
// 处理用户错误
}
if (settingsError) {
console.error('加载用户设置失败');
// 处理设置错误
}
// 即使其中一个失败,另一个成功的数据依然可用
if (userData) {
// ...
}
if (settingsData) {
// ...
}
}
使用 Promise.all
配合 to
函数,你可以优雅地处理多个 Promise 并发执行时部分成功、部分失败的场景,而传统的 try...catch
会在任何一个 Promise 失败时直接进入 catch
块,导致所有结果丢失。
其实并不是把try...catch给消灭了,只是to这个把try...catch给封装起来了
原文章:https://mp.weixin.qq.com/s/iBK0AUavQeRzOvKBbm7uCw