简体   繁体   中英

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM