I'm trying to insert a new document based on the request received and here's what I'm trying to do.
var function = (req,callBack)=>{
queryDB.findOne({query}).then((result)=>{
return(result); // see if requested object exists in DB and return if yes
}).then((result)=>{
if(condition:if required object exists){
updateDB.updateOne({query}).then((result)=>{ //update required object with new values
if(condition:update successful){
ref.function(value).then((k)=>{ // invoke for computation
return(k);
}).then((k)=>{
var document = new Document({ //create a new document
....
....
....
....
....
});
document.save().then((doc)={
callBack(doc); //return new document after successful insert
}).catch((err)=>{
updateDB.updateOne({query}).then((doc)=>{}) //revert back the update done earlier incase of error while inserting new document
callBack(err);
});
}).catch((error)=>{
updateDB.updateOne({query}).then((doc)=>{}) //revert back the update done earlier incase of error when invoked function has an error (2)
callBack(err);
})
}
}).catch((errorMessage)={
callBack(errorMessage);
})
}else{
callBack("Required Object Doesn't Exist");
}
}).catch((errorMessage)=>{
callBack(errorMessage);
})
}
The behavior I'm expecting is if there is an error in ref.function it should revert the update and send back error message but the API hangs indefinitely without reverting back the update done prior.
While the revert back works fine in-case of error in inserting new document to DB.