首页 > 解决方案 > 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.

解决方法是返回到第一次迭代并falseif (!token) return false该迭代中修复问题。

我的问题是

  1. 当我们通常不会显式返回 false 时,这是处理它的最佳方法吗?
  2. 我是 Typescript 的新手,返回类型是否Promise<undefined | User>合适?

类型用户包含id:字符串,用户名:字符串等...

标签: javascripttypescript

解决方案


回答你的问题,是的,有更好的方法。如果承诺的结果不是您期望的类型,您应该始终拒绝承诺。返回 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 undefinedreturn void 0也将有效。

从文档:

要求返回语句总是或从不指定值

参考:一致返回


推荐阅读