Promise<void> 的要求从何而来?

Where does this requirement for a Promise<void> come from?

我有一个辅助函数,它使用 fetch 从 API:

获取数据
const callApi = (endpoint: string, method = 'GET', body?: string): Promise<Response> => {
  // decide if url is dev or prod
  const url = getUrl()
  const headers = new Headers()
  headers.set('infinote-token', store.infinoteToken as string)
  const initObject = {
    headers: headers,
    method: method,
    body: method === 'POST' ? body : undefined
  }
  return fetch(`${url}${endpoint}`, initObject)
    .then(r => {
      if (r.ok) {
        apiIsOnline()
      } else if (r.status === 403) {
        store.needToSetToken = true
        apiIsOnline()
      } else {
        apiIsOffline()
        throw Error(r.statusText)
      }
    })
    .catch((reason) => {
      log.debug(`API call rejected because: ${reason}`)
      return Promise.reject()
    })
}

生成 TS 错误:

TS2322: Type 'Promise<void | Response>' is not assignable to type 'Promise<Response>'.    
          Type 'void | Response' is not assignable to type 'Response'.
            Type 'void' is not assignable to type 'Response'.

Promise<void> 的要求从何而来?

我的理解是fetch returns a Promise<Response>:

The promise resolves to the Response object representing the response to your request.

是的,取 return 一个 Promise<Response>。但是您正在使用 .then(r => ...) 处理此结果。此 r 是您从 fetch 返回的 Response。一个promise链的整体结果foo().then().then()...就是最后一个then()的结果。但是您的 then() 处理程序不会 return 任何东西(从技术上讲它会 return 和 Promise<void>)。因此,您 fetch(...).then(...) 的总体结果是 Promise<void>。如果您只想通过响应,请将 return r 添加到您的 then()

return fetch(`${url}${endpoint}`, initObject)
  .then(r => {
    if (r.ok) {
      apiIsOnline()
    } else if (r.status === 403) {
      store.needToSetToken = true
      apiIsOnline()
    } else {
      apiIsOffline()
      throw Error(r.statusText)
    }
    return r;
  })