【发布时间】:2020-02-29 04:17:50
【问题描述】:
我正在获取数组中指定的 URL,然后合并获取的结果。 我想忽略失败的提取。
虽然有大量关于该主题的帖子:
- Wait until all promises complete even if some rejected
- https://gist.github.com/nhagen/a1d36b39977822c224b8
我只是不知道如何将它应用到我的代码中,即从数组中获取 URL:
Promise.all (arrayOfBlobs.map (x => fetch (x).then (response => response.json())) )
.then (json => {
json.forEach ( x => {
if (Array.isArray (x)) {
// this json has array of objects
console.log (`Received ${x.length} prospects`)
x.forEach ( y => combinedArray.push (y) )
}
else {
// this json has single prospect object
console.log (`Received single prospect`)
combinedArray.push (x)
}
})
this.setState({loadingTable: false, data: combinedArray})
})
.catch (error => {
console.error (error.message)
this.setState({loadingTable: false, data: combinedArray})
})
例如下面的例子不起作用:
Promise.all (arrayOfBlobs.map (x => fetch (x).then (response => response.json())) )
.then (json => {
json.forEach ( x => {
if (Array.isArray (x)) {
// this json has array of objects
console.log (`Received ${x.length} prospects`)
x.forEach ( y => combinedArray.push (y) )
}
else {
// this json has single prospect object
console.log (`Received single prospect`)
combinedArray.push (x)
}
})
.catch (e => {console.log (`Failed to fetch due to ${e.message}`)})
this.setState({loadingTable: false, data: combinedArray})
})
.catch (error => {
console.error (error.message)
this.setState({loadingTable: false, data: combinedArray})
})
我需要做些什么来修改我的代码以便忽略失败的提取?
【问题讨论】:
-
尝试
fetch (x).then(response => response.json()).catch(() => "mark as failed")之类的,然后过滤。