javascript - eslint - 异步箭头函数返回值错误
问题描述
目前正在经历一些烦恼而不是问题。我有以下功能:
export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => {
const token = getTokenCookie(req)
if (!token) return
const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
const expiresAt = session.createdAt + session.maxAge * 1000
// Validate the expiration date of the session
if (Date.now() > expiresAt) {
throw new Error('Session expired')
}
return session
}
并eslint(consistent-return)
告诉我:Async arrow function expected no return value.
我想,为什么不试试这样呢:
export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => {
const token = getTokenCookie(req)
if (token) {
const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
const expiresAt = session.createdAt + session.maxAge * 1000
if (Date.now() > expiresAt) {
throw new Error('Session expired')
}
return session
}
}
但后来我得到了 eslint 的:Expected to return a value at the end of async arrow function.
解决方法是返回到第一次迭代并false
从if (!token) return false
该迭代中修复问题。
我的问题是
- 当我们通常不会显式返回 false 时,这是处理它的最佳方法吗?
- 我是 Typescript 的新手,返回类型是否
Promise<undefined | User>
合适?
类型用户包含id:字符串,用户名:字符串等...
解决方案
回答你的问题,是的,有更好的方法。如果承诺的结果不是您期望的类型,您应该始终拒绝承诺。返回 undefined 仍然会让该承诺的调用者处理这种情况,这在我的经验中变得有点令人困惑。
我会把它改成这样:
export const getLoginSession = async (req: NextApiRequest): Promise<User> => { // <-- this promise will return a user or throw
const token = getTokenCookie(req)
if (!token) {
throw new Error('invalid token') // <-- unexpected we should throw
}
const session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults)
const expiresAt = session.createdAt + session.maxAge * 1000
// Validate the expiration date of the session
if (Date.now() > expiresAt) {
throw new Error('Session expired')
}
return session
}
这样我们就有了更好的控制流程,而且很容易推理。
try {
const session = await getLoginSession(req)
// do something with the session
} catch (error) {
// handle the error
console.log(error)
}
关于一致返回,是因为你没有在返回之后定义一个值。所以return false
有效,但return undefined
或return void 0
也将有效。
从文档:
要求返回语句总是或从不指定值
参考:一致返回
推荐阅读
- primefaces - 尽管在 primefaces p:cellEditor 中具有相同的表达式,但 h:outputText 中的 JSF2 ValueExpression 不会评估为 true
- sql-server - 如何将二进制列数据读入火花数据帧?
- c# - 将 retryPolicy 与 SqlAzureExecutionStrategy 一起使用时,避免“SqlParameter 已被另一个 SqlParameterCollection 包含”异常
- mysql - 带有'n'个条件的Mysql查询用NOT括起来
- arrays - 在 Tableview (Swaft) 上获取重复的 Firestore 文档
- typescript - TypeScript 的 Visual Studio Code 自动导入行为不一致
- azure - 增加 Kubernetes 中状态集的 PVC 大小
- amazon-web-services - 如果key为空,则只允许一个ApiMapping
- javascript - 如何在单击复选框上显示多个 div
- linux - 如何设置电源按钮行为以关闭 linux 中的显示?