如何在Promise中获取结果数组的所有错误

时间:2017-10-27 06:34:01

标签: javascript promise

有没有办法在Promise.all.catch上获得结果对象?

我想在数据库中进行两次插入,一次在MySQL数据库中,一次在MongoDB数据库中。如果其中一个失败了,我想删除另一个。

这是一些伪代码

const mysqlPromise = mysql.query('insert to table')
const mongoPromise = mongodb.insert('insert to collaction')
Promise.all([mysqlPromise,mongoPromise])
.then(result =>{

})
//i know it doesnt work that way but this is what i need to achive
.catch((err,result) =>{

    if(err[0] && err[1]){
      //do nothing
      return 
    }
    if(err[0]){
      mongodb.delete({_id:result[1].insertId})
    }
    else{
      mysql.query('delete from table where id = 'result[0].lastInsertId)
    }
    
})

1 个答案:

答案 0 :(得分:2)

我认为你想要的东西不是,而是,但是你可以在all运算符之后捕获它们之前操纵你的单一承诺:

Promise.all([
  mysqlPromise.catch(err => new Error('mysql failed')),
  mongoPromise.catch(err => new Error('mongo failed')),
])
.then(result => {
  const mysqlFailed = result[0] instanceof Error;
  const mongoFailed = result[1] instanceof Error;

  if (mysqlFailed && mongoFailed) {
    // nothing
  } else if (mysqlFailed){
    mongodb.delete({_id:result[1].insertId})
  } else if (mongoFailed) {
    mysql.query('delete from table where id = 'result[0].lastInsertId)
  } else {
    // success
  }
})