Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

46
Views
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 .

6 months ago · Santiago Gelvez
2 answers
Answer question

0

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

6 months ago · Santiago Gelvez Report

0

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

result inside .then is the response you receive on success. You can't apply condition on the fly inside function parameters. You have to check inside the callback function. If results will have id (result?.id) then this.triggerAction(result.id) will invoke

I hope it will work.

Thanks :)

6 months ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.