简体   繁体   English

如何重用http请求结果?

[英]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. 我的问题是,如果hasProduct为false,我仍然需要发出请求以获取产品名称,但是我不希望在不同条件下发出两个相同的请求是可行的。 I was wondering if there is a better way to do it. 我想知道是否有更好的方法。 Thanks for the help! 谢谢您的帮助!

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: 如果hasProduct变量发生变化(例如在循环中),则可以像这样包装回调函数,这样hasProduct变量将被绑定:

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

You can refactor your code to use the hasProduct value after the request completes. 请求完成后,可以重构代码以使用hasProduct值。 But if you do that: 但是,如果这样做:

Please, use an IIFE closure: 请使用IIFE闭包:

(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. 通过使用IIFE闭包,可以保留hasProduct的值,并在请求的承诺解决时可用。 This avoids bugs caused by hasProduct changing between the initiation of the request and the completion of the request. 这避免了hasProduct在请求的发起和请求的完成之间发生更改而导致的错误。

For more information Immediately-invoked function expressions 有关更多信息, 立即调用函数表达式

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

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