首页 > 解决方案 > 发生 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 不会解析。请问我该如何处理?

谢谢你的帮助 !

标签: javascriptes6-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() {
    // ...
  }

  
}))

推荐阅读