BonJon
BonJon

Reputation: 799

How to reuse http request result?

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!

Upvotes: 1

Views: 129

Answers (2)

georgeawg
georgeawg

Reputation: 48968

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

Upvotes: 2

Tennyson H
Tennyson H

Reputation: 1716

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));

Upvotes: 3

Related Questions