promise.all 不拒绝失败的获取请求[重复]

问题描述 投票:0回答:1

例如:

  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.log
ing
settings
会返回类似以下内容:

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

...并且

Promise.all
成功,不会拒绝 Promise。

当请求失败时如何使其拒绝?

javascript promise fetch-api
1个回答
1
投票

fetch
不会拒绝失败请求的承诺,所以你必须附加一个处理程序,来决定请求是否成功:

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()))
© www.soinside.com 2019 - 2024. All rights reserved.