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

inkz8wg9  于 2023-09-29  发布在  Java
关注(0)|答案(1)|浏览(99)

这个问题已经有答案了

try..catch not catching async/await errors(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。
当请求失败时,我如何使其拒绝?

gdx19jrr

gdx19jrr1#

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()))

相关问题