【发布时间】:2018-04-01 16:40:04
【问题描述】:
我正在尝试使用此 fetch() 函数在 Chrome 中处理 404。
function promiseBatchDomains(domainsToQuery) {
var batchSize = domainsToQuery.length
var currentDomain = 0
var promises = domainsToQuery.map(domain => (
fetch(`https://api-url-omitted/${domain}`)
.then( res => {
if (res.ok) {
return res
} else {
throw Error(res.statusText)
}
})
.then(res => res.json())
.then(res => {
currentDomain += 1
console.log(currentDomain + " of " + batchSize + ': ' + domain + ' data received.')
percentCompletion = parseFloat(currentDomain / batchSize).toLocaleString(undefined,{style: 'percent'})
$('#batchProgressBar').attr('aria-valuenow', percentCompletion).width(percentCompletion)
return res
})
.then(res => ({ domain, res })
.catch(error => console.log("Error: " + error))
))).filter(Boolean)
Promise.all(promises)
.then(results => makeCSV(results))
}
我需要帮助来理解为什么我在 if/else 语句中抛出的错误没有被 catch 捕获。
基于here、here、here 和 here 概述的方法,我尝试了几种不同的方法:通过抛出错误,如我上面的代码中,以及Promise.reject()。无论哪种方式它都会挂起,所以我想知道我是否遗漏了一些更基本的东西。
在我的控制台中,我只看到原始的 404,但没有看到来自我的错误的 console.log,我相信如果触发了 catch,它应该会触发。 (当它不是 404 时,此函数的其余部分按预期工作。)
更新:我用这样的 if 语句重构了第三个 .then() 方法:
.then(res => {
currentDomain += 1
if (domain) {
console.log(currentDomain + " of " + batchSize + ': ' + domain + ' data received.')
percentCompletion = parseFloat(currentDomain / batchSize).toLocaleString(undefined,{style: 'percent'})
$('#batchProgressBar').attr('aria-valuenow', percentCompletion).width(percentCompletion)
return {domain, res}
}
})
现在捕获触发。 throw Error() 不应该让它跳过所有.then() 方法并直接出错吗?
【问题讨论】:
-
我很想知道如果您将
catch添加到Promise.all(promises).then(...)会发生什么 -
@user3405291 我试了一下,但该功能永远不会走那么远,因为它挂在未捕获的 404 上。
标签: javascript error-handling fetch