例如:
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。
当请求失败时如何使其拒绝?
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()))