有什么方法可以获取 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)
}
})
最佳答案
我不认为你想要的东西是真正可用的原样,但是你可以在 all
运算符之后捕获它们之前操纵你的单一 promise :
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
}
})
关于javascript - 如何在 Promise all 错误中获取结果数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46968833/