Home > front end >  Commit delete operation only if another async operation succeeds
Commit delete operation only if another async operation succeeds

Time:09-09

While working with mongoose, I have the following two async operations

const user = await userModel.findOneAndDelete(filter, options);
await anotherAsyncFunctionToDeleteSomething(user); // not a database operation

But I need to ensure that both deletions happen or reject together. I've thought about putting trycatch on second function and recreate the user document if any error is caught (in the catch block). However, this doesn't seem like an efficient (or at least appealing) solution.

CodePudding user response:

If second operation is totally unrelated then there's nothing much you can do. You can later ensure if both records were if that's extremely necessary. You could use Promise.all() to run both promises simultaneously but it'll throw error if either fails so you can retry it. But as you mentioned, you need result of first operation before running the second then you'll have to run those individually.

Yes, you can catch any errors thrown in the second promise and recreate a document with same ID as shown below:

const user = await userModel.findOneAndDelete(filter, options);

try {
  await anotherAsyncFunctionToDeleteSomething(user);
} catch (e) {
  console.log(e)
  await collection.insertOne({ _id: new ObjectId("62....54"), ...otherData });
}
  • Related