目前正在经历一些烦恼而不是问题。我有以下功能:
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
以解决问题。
我的问题是
Promise<undefined | User>
的返回类型是否合适?type User contains id: string, username: string, etc...
答案 0 :(得分:0)
回答您的问题,是的,有更好的方法。如果承诺的结果不是你期望的类型,你应该总是拒绝承诺。返回 undefined 仍然会让那个 Promise 的调用者处理这种情况,这在我的经验中变得有点混乱。
我会改成这样:
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
也有效。
来自文档:
<块引用>要求 return 语句始终或从不指定值
答案 1 :(得分:0)
在下面的代码中,当您返回时,session
不存在,const/let
值是块范围的,因此 session
范围仅存在于该 if
块内而不存在于外部其中。你也需要。从 if
块内部返回并返回错误承诺或仅在 token
获得 falsy
时执行回退,如果没有则返回 session
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
}