[英]Promise.allSettled returns catch as fullfilled
I am making https requests using a function batchRequest
that collects the promises in batches with Promise.allSettled
and sends them to the apiRequest
function that makes the actual calls with axios.我正在使用 function
batchRequest
发出 https 请求,它使用Promise.allSettled
分批收集承诺,并将它们发送到apiRequest
function,后者使用 axios 进行实际调用。
On the batchRequest
function I send an array of urls to the HTTP request function and await the results.在
batchRequest
function 上,我向 HTTP 请求 function 发送了一个 url 数组并等待结果。 Then I use the Promise.allSettled
status
to identify the rejected
ones.然后我使用
Promise.allSettled
status
来识别被rejected
的。 But when the apiRequest
catches as error Promise.allSettled
sees it as status: fullfilled
但是当
apiRequest
捕获为错误Promise.allSettled
时,将其视为status: fullfilled
fullfilled
async function batchRequest(data, index) {
console.log(`Running... ${index} round`)
while (data.length) {
// Batched request according to concurrent setting
const batch = data
.splice(0, settings.concurrent)
.map((url) => apiRequest(url, index))
const results = await Promise.allSettled(batch)
results.forEach(({ status, value, reason }) => {
if (status === 'fulfilled') {
console.log(value) // I get both the try and catch here from `apiRequest`
}
if (status === 'rejected') {
console.log(reason)
// I never get anything here
}
})
}
}
Api request function Api 请求 function
async function apiRequest(url, index) {
try {
const { data } = await axios('https://api-end-point')
return 'All good' + url
} catch (error) {
const status = error.response?.status ?? 'No response'
return `Error: ${status}, ${url}`
}
}
Don't return the error.不要返回错误。 throw it!
丢它!
async function apiRequest(url, index) {
try {
const { data } = await axios('https://api-end-point')
return 'All good' + url
} catch (error) {
const status = error.response?.status ?? 'No response'
throw `Error: ${status}, ${url}` // <------------change here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.