Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to check conditions inside .then in javascript

Existing code(Working fine) :

.then((result) => { 
                this.triggerAction(result.id); 
            }).catch((error) => { 
              this.errorMsg(error);
            });

when i try to add condition inside the .then throws error.

.then((result && result.id) => {
               this.triggerAction(result.id); 
            }).catch((error) => { 
              this.errorMsg(error);
            });
        

I need to check both result and result.id is coming in the response and throws error id if not available in the result .

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To throw an error if result.id is missing, you should do the following:

          .then((result) => {
            if(!result.id) {
               throw new Error("result.id is missing!");
            }
            this.triggerAction(result.id); 
          }).catch((error) => { 
            this.errorMsg(error);
          });

You can also do throw result if you just want to pass result to the .catch() block

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading