gpt4 book ai didi

javascript - 当函数已经捕获错误时知道异步函数是成功还是失败?

转载 作者:行者123 更新时间:2023-12-03 00:41:46 25 4
gpt4 key购买 nike

我设置了应用程序的结构,在其中使用类似这样的函数,这些函数的范围为“Auth”,例如:

  async function authenticate(email) {
let success = false;
try {
if (email) {
if (!validEmail(email)) {
console.error('Invalid email');
} else {
await APIAuthenticate(email);
success = true;
}
}
} catch (error) {
console.error(error)
}
return success;
}

正如您所看到的,success 变量存在一个不便之处,它之所以存在,是因为我需要在另一个 View 文件中使用 authenticate 函数,以便在身份验证完成后重新路由用户成功(我不想在 authenticate 函数本身内重新路由用户,以便将它们作为单独的关注点,并且不将路由逻辑导入到 auth 中)。

目前我是这样使用的

// MyView.js
const success await authenticate("some@email.com");
if (success) {
router.push("/dashboard")
}

一般来说它是有效的,但我想问是否有一个解决方案不需要我手动跟踪 authenticate() 函数内的 success 变量?

最佳答案

不确定您的意思到底是什么,但 authenticate() 中实际上不需要 success 。只需使用 throwcatch 来处理即可。

  async function authenticate(email) {
try {
if (email) {
if (!validEmail(email)) {
throw new Error('Invalid email');
} else {
await APIAuthenticate(email);
}
}
} catch (error) {
console.error(error)
return false;
}
return true;
}

关于javascript - 当函数已经捕获错误时知道异步函数是成功还是失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53428233/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com