Is this a good way of breaking “THEN chain” when using promises?

109
June 06, 2019, at 8:20 PM

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?

Answer 1

You could do as follows:

  const p1 = db.collection('products').doc(productId).get();
  const p2 = db.collection('user_data').doc(userUid).get();
  const 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');
        throw new Error(ErrorCodes.UNKNOWN_PRODUCT);
      }
      if (!userDataDoc.exists) {
        console.log('User data block not found!');
        throw new Error(ErrorCodes.UNKNOWN_USER_DATA);
      }
      variantCountryRef = db.doc(
        'products/' + productId + '/variants/' + variantCountry
      );
      return variantCountryRef.get();
    })
    .then(variantCountryDoc => {
         //Don't forget to send a response back to the client, see https://www.youtube.com/watch?v=7IkUgCLr5oA&
         //...
         //response.send(...);
    })
    .catch(err => {
      if (err.message === ErrorCodes.UNKNOWN_PRODUCT) {
        response.status(404).json({
          error: ErrorCodes.UNKNOWN_PRODUCT,
          msg: 'The products does not exist'
        });
      } else if (err.message === ErrorCodes.UNKNOWN_USER_DATA) {
        response
          .status(404)
          .json({
            error: ErrorCodes.UNKNOWN_USER_DATA,
            msg: 'User data block not found!'
          });
      } else {
        //Deal with other error types
      }
    });
READ ALSO
How to find and edit a session with express-session and connect-mongo?

How to find and edit a session with express-session and connect-mongo?

I use express-session and connect-mongo to deal with user sessions

119
How to redirect back to a page when wrong file type has been uploaded via multer in NodeJS

How to redirect back to a page when wrong file type has been uploaded via multer in NodeJS

Im trying to handle if the wrong file type is uploaded via multer to redirect back to the main page with an error message stored in a passed variable

114
Sum of a document fields mongodb

Sum of a document fields mongodb

I need to find the sum of some specified fields using the following logic: Find document where sum of (score_one1+ score_one

123
Loopback 3 / Where Filter / LIKE / MSSQL Connector Error

Loopback 3 / Where Filter / LIKE / MSSQL Connector Error

I'm using the mssql connector and can't get any hits using the LIKE operatorI've tried all sorts of combinations

157