1

Is there any way to get the result object on Promise.all.catch?

I'd like to do two inserts in a database, one in a MySQL database and one in a MongoDB database. If one of them fails I'd like to delete the other one.

Here is some pseudo code

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)
    }
    
})
Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
Amit Wagner
  • 3,134
  • 3
  • 19
  • 35
  • and what if delete also fails? :) – smnbbrv Oct 27 '17 at 06:42
  • i can do a loop to retry every x seconds , its not perfect but i can live with that the chances this case will happen is rely low . what i try to achieve is a transaction on 2 different dbs this is the closest thing i can think of – Amit Wagner Oct 27 '17 at 06:48
  • Have a look at [Wait until all ES6 promises complete, even rejected promises](https://stackoverflow.com/q/31424561/1048572) which allows you to observe the individual outcomes – Bergi Oct 27 '17 at 07:37

1 Answers1

2

I don't think the thing you want is really available as is, however you can manipulate your single promises before catching them after all operator:

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
  }
})
smnbbrv
  • 23,502
  • 9
  • 78
  • 109