Home > Back-end >  how to check conditions inside .then in javascript
how to check conditions inside .then in javascript

Time:07-16

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 .

CodePudding user response:

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

CodePudding user response:

.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 :)

  • Related