简体   繁体   English

在返回时将三元运算符转换为if else语句

[英]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 return (product) ? product

I believe that this is best done with an if else statement. 我相信最好通过if else语句来完成。 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 (return ...) If you want to rewrite it to a if else statement, you can use this: 如果要将其重写为if else语句,则可以使用以下命令:

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 . 请注意,是不是有必要if else ,如果if条件符合,else部分将永远不会为我们达成return里面if So you can just return inside the if and don't need an else thereafter. 因此,您可以只在if return ,此后不需要else

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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