I have a simple "then chain" that runs some functinality steps. If some condition is met I need to cancel the chain and exit (mainly if an error occurrs). I'm using this in a firebase cloud function, but I think it is a basic concept applicable to any node/express eviroment.
This is the code I have:
let p1 = db.collection('products').doc(productId).get();
let p2 = db.collection('user_data').doc(userUid).get();
let promises= [p1,p2];
return Promise.all(promises)
.then(values =>
{
let proudctDoc = values[0];
let userDataDoc = values[1];
if(!proudctDoc.exists)
{
console.log("The product does not exist");
response.status(404).json({error: ErrorCodes.UNKNOWN_PRODUCT, msg: "The products does not exist"});
throw("CANCEL");
}
if(!userDataDoc.exists)
{
console.log("User data block not found!");
response.status(404).json({error: ErrorCodes.UNKNOWN_USER_DATA, msg: "User data block not found!"});
throw("CANCEL");
}
variantCountryRef = db.doc('products/'+productId+'/variants/'+variantCountry);
return variantCountryRef.get();
})
.then(variantCountryDoc =>
{
....
})
.catch(err =>
{
if(err !== "CANCEL")
{
//Deal with real error
}
}
As you see, I just run 2 promises and wait for them to finish. After this I check some returned values and notify the client if an error occurs. At this time I must finish the "Then chain".
Is this a common pattern? Anything I could improve?