简体   繁体   中英

Turning a ternary operator into if else statement on return

I'm currently using a ternary operator as follows:

return $scope.productWithEAN(EAN).then(function(product) {
   return (product) ? product : $scope.createProduct(productID, name);
  });
});

I want to now point to a function if return (product) ? product return (product) ? product

I believe that this is best done with an if else statement. I have created this, however I am getting an unexpected return token:

return $scope.productWithEAN(EAN).then(function(product) {
  if (return (product) ? product) {
      console.log("product is here");
      //$scope.checkOrUpdateProduct;
    },else {
      console.log("product not here");
      //$scope.createProduct(productID, name);
    };
  });
});

Is there a better way of doing this?

You can't use if (return ...) . If you want to rewrite it to a if else statement, you can use this:

return $scope.productWithEAN(EAN).then(function(product) {
    if (product) {
        console.log("product is here");
        return $scope.checkOrUpdateProduct();
    } 
    console.log("product not here");
    return $scope.createProduct(productID, name);
});

Note that there isn't the need of if else , if the if condition meets, the else part will never be reached as we return inside the if . So you can just return inside the if and don't need an else thereafter.

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