promise.all 不拒绝失败的获取请求

promise.all does not reject failed fetch requests

例如:

  const settingPromises = Object.keys(values).map(key => {
    return fetch(`${client}/settings`, {
      signal,
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        authorization: `Bearer ${token}`
      },
      body: JSON.stringify({
        name: _.kebabCase(key),
        value: values[key]
      })
    })
  })

  const settings = await Promise.all(settingPromises)
  const results = await Promise.all(settings.map(setting => setting.json()))

如果一次获取失败,console.loging settings returns 类似于:

settings -- (2)[Response, Response]
[
  {
    type: 'cors',
    url: 'api.example/settings',
    redirected: false,
    status: 400,
    ok: false,
    statusText: 'Bad Request',
    ...
  },
  ...
]

...并且 Promise.all 成功,不拒绝 Promise。

如何让它在请求失败时拒绝?

fetch won't reject its promise on failed requests,所以你必须附加一个处理程序,它决定请求是否成功:

const settingPromises = Object.keys(values).map(key => {
    return fetch(`${client}/settings`, {
      signal,
      method: 'POST',
      headers: {
        'content-type': 'application/json',
        authorization: `Bearer ${token}`
      },
      body: JSON.stringify({
        name: _.kebabCase(key),
        value: values[key]
      })
    }).then(response => {
      if(response.ok) return response
      throw response
    })
  })

  const settings = await Promise.all(settingPromises)
  const results = await Promise.all(settings.map(setting => setting.json()))