簡體   English   中英

eslint - 異步箭頭 function 返回值錯誤

[英]eslint - async arrow function return value error

目前正在經歷一些煩惱而不是問題。 我有以下 function:

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.

解決方法是返回第一次迭代並從if (!token) return false false返回 false,從而解決了問題。

我的問題是

  1. 當我們通常不會顯式返回 false 時,這是處理它的最佳方法嗎?
  2. 我是 Typescript 的新手,返回類型為Promise<undefined | User> Promise<undefined | User>合適嗎?

類型用戶包含id:字符串,用戶名:字符串等...

回答你的問題,是的,有更好的方法。 如果 promise 的結果不是您期望的類型,您應該始終拒絕 promise。 返回 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 undefinedreturn void 0也可以。

從文檔:

要求返回語句總是或從不指定值

參考:一致返回

在下面的代碼中,返回時session不存在, const/let值是塊范圍的,因此session scope 僅存在於該塊內部, if不在該塊之外。 你也需要。 if塊返回內部並返回錯誤 promise 或僅在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
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM