1

Hi I am trying to make requests for my codes.

I have something like

if(hasProduct) {
    product.getProduct(, function(product) {
        $scope.name = product.name;
        $scope.price = product.price;
        $scope.region = product.region;
        //do other things.
    })
} else {
     product.getProduct(, function(product) {
         $scope.name = product.name;   // I need to get product name whether hasProduct is true or false
    })
    //do something
}

my question is if hasProduct is false, I still need to make a request to get the product name but I don't feel like making two identical requests in different condition is practical. I was wondering if there is a better way to do it. Thanks for the help!

1
  • Just as a matter of style, it's usually better to just store the resource (body of the http request) in the scope instead of storing each little bit of it. Then use $watch to respond to changes in its fields. Commented Nov 24, 2015 at 21:37

2 Answers 2

3

You can make one request and use the variable in the callback to branch your logic.

product.getProduct(, function(product) {
    if (hasProduct) //do stuff
    else //do other stuff
});

If the hasProduct variable changes (like if it's in a loop) you can wrap the callback function like so, this way the hasProduct variable is bound:

product.getProduct(, (function(hasProduct) { return function(product) {
    if (hasProduct) //do stuff
    else //do other stuff
})(hasProduct));
Sign up to request clarification or add additional context in comments.

Comments

2

You can refactor your code to use the hasProduct value after the request completes. But if you do that:

Please, use an IIFE closure:

(function (hasProduct) {
    product.getProduct(, function(product) {
        //Executed asynchronously after request completes
        $scope.name = product.name;
        if (hasProduct) {
             $scope.price = product.price;
             $scope.region = product.region;
            //do other things.
        };
    });
})(hasProduct);

By using an IIFE closure, the value of hasProduct is preserved and available when the request's promise resolves. This avoids bugs caused by hasProduct changing between the initiation of the request and the completion of the request.

For more information Immediately-invoked function expressions

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.