axios.all 多个请求同时报错 catch不到

catch 不到多个报错信息 两个请求都返回了报错状态

axios.all([this.getFormData(),this.getFormHead()]).then(axios.spread((fromDataResp, formHeadResp)=> {
                        console.log("成功")
                }))
                    .catch(error=>{
                    console.log(error,'只能打印第二条报错')
                })

试过这样也不行

axios.all([this.getFormData(),this.getFormHead()]).then(axios.spread((fromDataResp, formHeadResp)=> {
                        console.log("成功")
                })).catch(axios.spread((fromDataerr, formHeaderr) => {
                    console.log(fromDataerr)//underfind
                    console.log(formHeaderr)//underfind
                }))

有大佬能指点一下吗???

阅读 6.1k
2 个回答

使用Promise.allcatch每一个函数。结果统一处理

;!async function () {
  let res = await Promise.all([
    fun01().catch(err => err),
    fun02().catch(err => err),
    fun03().catch(err => err),
  ])

  console.log('res', res); // ["成功:11111", "失败:22222", "成功:33333"]

  function fun01 () {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('成功:11111')
      }, 2000)
    })
  }

  function fun02 () {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject('失败:22222')
      }, 2000)
    })
  }

  function fun03 () {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('成功:33333')
      }, 2000)
    })
  }
} ();

Promise.all() 语法也只能 catch 第一个发生错误的 promise。想 catch 多个,在 Stack Overflow 搜索了一下,可这样改造使用

const promises = [
  axios.get('http://some_url'),
  axios.get('http://another_url'),
]
const promisesResolved = promises.map(promise => promise.catch(error => ({ error })))

function checkFailed (then) {
  return function (responses) {
    const someFailed = responses.some(response => response.error)

    if (someFailed) {
      throw responses
    }

    return then(responses)
  }
}

axios.all(promisesResolved)
  .then(checkFailed(([someUrl, anotherUrl]) => {
    console.log('SUCCESS', someUrl, anotherUrl)
  }))
  .catch((err) => {
    console.log('FAIL', err)
  });

@gauseen

推荐问题