javascript - 发生 404 时处理 Promise 未解决
问题描述
我是 Promise 的新手。
我有一个 fetch() 函数的 vuejs 组件,如下所示:
async fetch () {
this.loadingDetails = true
const products = await Promise.all(this.items.map((item) => {
try {
const products = this.$wizaplace.get('/catalog/products/' + item.declinationId.slice(0, 4), { // When the ID is incorrect, a 404 is returned
lang: this.$i18n.locale
})
console.log(products)
} catch (e) {
// eslint-disable-next-line no-console
console.log('Error Fetching profile: ', e)
}
return products
}))
console.log(products)
this.productsDetails = products.map((product) => {
console.log(product)
const generalAttributes = product.attributes.find(attr => attr.id === 49)
const brewerie = generalAttributes.children.find(attr => attr.id === 59)
const color = generalAttributes.children.find(attr => attr.id === 15)
// console.log(product)
return {
attributes: product.attributes,
brewerie: (brewerie && brewerie.value[0]) ? brewerie.value[0] : '',
type: generalAttributes.children.find(attr => attr.id === 47).value[0],
color: (color && color.value[0]) ? color.value[0] : ''
}
})
this.loadingDetails = false
// console.log(this.productsDetails[0])
},
当 Promise.All(callback) 中的一个 HTTP 调用失败时,Promise 不会解析。请问我该如何处理?
谢谢你的帮助 !
解决方案
您在 try 块之外退回产品
你必须改变它
const products = await Promise.all(this.items.map((item) => {
try {
const products = ...
// ...
} catch() {
// ...
}
return products
}))
接着就,随即
const products = await Promise.all(this.items.map((item) => {
try {
const products = ...
// ...
return products
} catch() {
// ...
}
}))
推荐阅读
- python - 在pygame中实现定时器
- android - 检查媒体播放器
- amazon-web-services - Aws 将值从 Lambda 触发器传递到 Step Function
- r - 从列表 R 中删除特定变量
- c# - Automapper 常用地图部分
- python - 在 Python 中读取 .csv 文件
- android - 我可以模拟一个字段没有 getter 属性的类吗
- android - 找不到材料芯片的“app:closeIconVisible”
- php - 使用 htaccess 删除 .php 扩展名,但保留 /index.php 功能
- python - Keras plot_model() 函数:更精细的输出