angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

Can no longer cancel $resource request with a promise

Open simonjm opened this issue 12 years ago • 20 comments

I've tested this on Chrome 37.0.2062.124 m, Firefox 32.0.3, and IE11 on Windows 8.1

Here is some code to reproduce the issue.

<body ng-app="testApp">
    <div ng-controller="TestCtrl">
        <button type="button" ng-click="clear()">Clear</button>
        <ul>
            <li ng-repeat="val in dataset">
                {{val | json}}
            </li>
        </ul>
        <button type="button" ng-click="start()">Start</button>
        <button type="button" ng-click="stop()">Stop</button>
    </div>
    <script type="text/javascript" src="https://code.angularjs.org/1.3.0-rc.3/angular.js"></script>
    <script type="text/javascript" src="https://code.angularjs.org/1.3.0-rc.3/angular-resource.js"></script>
    <script type="text/javascript">
        angular.module('testApp', ['ngResource']).controller('TestCtrl', function ($scope, $resource, $q) {                                   
            var promises = [];
            function getResource() {
                var defered = $q.defer();
                promises.push(defered);
                return $resource('/data', {}, {
                    query: {
                        method: 'GET',
                        isArray: true,
                        timeout: defered.promise
                    }
                });
            }

            $scope.start = function () {
                getResource().query(function (res) {
                    $scope.dataset = res;
                });
            };

            $scope.stop = function () {
                promises.forEach(function (p) { p.resolve(); });
                promises = [];
            };

            $scope.clear = function() {
                $scope.dataset = [];
            }
        });
    </script>
</body>

https://github.com/angular/angular.js/commit/23bc92b17df882a907fb326320f0622717fefe7b appears to be the culprit. Before this the above code works as expected.

simonjm avatar Sep 29 '14 21:09 simonjm

there are tests in the tree which assert that this does work, so it seems something else is wrong with your code. I'm not sure what at the moment, however

caitp avatar Sep 29 '14 22:09 caitp

I think the main problem with this is that you end up trying to resolve your promise more than once, but I'm not really positive here

caitp avatar Sep 29 '14 22:09 caitp

@lgalfaso does this seem like a bug to you? on the one hand the API doesn't seem super useful of the promise can only be resolved once --- on the other hand, it doesn't seem to be working at all, so I must be missing something about why this is broken

caitp avatar Sep 29 '14 22:09 caitp

yeah I noticed this recently as well. I altered the same code to use $http and all was well.

I did a quick search and did not see a $resource test that actually uses {timeout: promise} as a config value, though so maybe we are not testing for it properly.

On Mon, Sep 29, 2014 at 6:53 PM, Caitlin Potter [email protected] wrote:

@lgalfaso https://github.com/lgalfaso does this seem like a bug to you? on the one hand the API doesn't seem super useful of the promise can only be resolved once --- on the other hand, it doesn't seem to be working at all, so I must be missing something about why this is broken

— Reply to this email directly or view it on GitHub https://github.com/angular/angular.js/issues/9332#issuecomment-57242799.

Josh Kurz www.joshkurz.net

joshkurz avatar Sep 29 '14 23:09 joshkurz

there is no resource test for this, but I think it's weird to use this for resource, because you're configuring it once, and then that promise is basically permanently cancelled if it ever gets cancelled --- which isn't super useful

caitp avatar Sep 29 '14 23:09 caitp

true, but you could just create another one if you wanted too. I think canceling requests is very useful. I use it all the time. If a request is made, while another is going on, I just resolve and create a new promise object to use as the timeout value. This works really well.

Your thinking about passing the {timeout: promise} another way, other than request's config?

On Mon, Sep 29, 2014 at 7:19 PM, Caitlin Potter [email protected] wrote:

there is no resource test for this, but I think it's weird to use this for resource, because you're configuring it once, and then that promise is basically permanently cancelled if it ever gets cancelled --- which isn't super useful

— Reply to this email directly or view it on GitHub https://github.com/angular/angular.js/issues/9332#issuecomment-57245158.

Josh Kurz www.joshkurz.net

joshkurz avatar Sep 29 '14 23:09 joshkurz

well, you'd have to give $resource a factory for creating a cancelled promise, and $resource would have to expose a way to resolve that factory-created promise, otherwise you'd have to rely on hacks to make that work.

I think if we want to have an API like this, it needs to be reworked, because this is crazy.

But again, I'm still not even sure that this is actually the problem they're having, it's very hard to debug this.

caitp avatar Sep 29 '14 23:09 caitp

Maybe this is a better example of the problem. If I update the $scope.start function to this

            $scope.start = function () {
                var defered = $q.defer();
                $timeout(function() { defered.resolve(); }, 2);
                $http.get('/data', {timeout : defered.promise}).success(function(res) {
                    $scope.dataset = res;
                });
            };

The request is cancelled as expected. Now if I update $scope.start to use $resource

            $scope.start = function () {
                var defered = $q.defer();
                $timeout(function() { defered.resolve(); }, 2);
                $resource('/data', {}, {
                    query : {
                        method : 'GET',
                        isArray : true,
                        timeout : defered.promise
                    }
                }).query(function(res) {
                    $scope.dataset = res;
                });
            };

The request doesn't get cancelled.

simonjm avatar Sep 30 '14 00:09 simonjm

None of this is really helpful in debugging this, and I can't think of a reason why this would have worked before --- unless we previously did let you resolve promises more than once, and I'm pretty sure we didn't. I am not seeing what changed, but I am seeing that this API didn't make any sense before, and it definitely needs some changes to be really useful to people. Unfortunately, even with the changes I'm thinking of, you'd only ever be able to cancel the most recent request that was made, which might not be what people want to do. So it's really hard to make this work "well"

caitp avatar Sep 30 '14 01:09 caitp

@caitp Is it wanted behavior that only defaults.transformRequest defaults.transformResponse and default.withCredentials are passed to the config in function https://github.com/angular/angular.js/blob/master/src/ng/http.js#L706 (sorry for using lines in links) .. just adding timeout: defaults.timeout will do.

guilbep avatar Oct 16 '14 14:10 guilbep

well again, defaults.timeout would only actually work right if it was a number (which is what you'd expect from a timeout variable) --- but if it were a promise, this would never work right. So I guess yeah that's probably the main reason why we don't include it.

caitp avatar Oct 16 '14 14:10 caitp

@caitp That's not nice. Maybe we should add a section into the documentation that says so. I could maybe do it if you think that's right. https://docs.angularjs.org/api/ng/provider/$httpProvider ?

guilbep avatar Oct 16 '14 15:10 guilbep

This is a very valuable article, around which I have created my own duplicate request aborter service.

https://developer.rackspace.com/blog/cancelling-ajax-requests-in-angularjs-applications/

@caitp: Does it mean that from 1.3 on this will not be possible anymore?

tsonev avatar Jan 06 '15 14:01 tsonev

I tracked down this issue to resource.js, 563:


            forEach(action, function(value, key) {
              if (key != 'params' && key != 'isArray' && key != 'interceptor') {
                httpConfig[key] = copy(value);
              }
            });

The function clones all config values except some with special treatment. The timeout promise is currently getting cloned. So, when httpBackend.js, 115 receives the timeout,


    } else if (isPromiseLike(timeout)) {
      timeout.then(timeoutRequest);
    }

It actually registers that callback on a clone, which never gets resolved.

I made a quick & dirty fix which doesn't clone but just assigns a 'timeout' property in the iteration above, and issue gets resolved.

valente avatar Apr 23 '15 20:04 valente

:+1: @valente

qpitlove avatar Jun 08 '15 12:06 qpitlove

any workaround for this?

psergus avatar Aug 28 '15 23:08 psergus

I've crafted a promise that can be cancelled so that I can ignore the ajax request result if need be.

On Sat, 29 Aug 2015 at 09:46 Sergey Petrenko [email protected] wrote:

any workaround for this?

— Reply to this email directly or view it on GitHub https://github.com/angular/angular.js/issues/9332#issuecomment-135915613 .

kayhadrin avatar Aug 29 '15 03:08 kayhadrin

yeah, I was playing with the promise as well and following this example https://developer.rackspace.com/blog/cancelling-ajax-requests-in-angularjs-applications/ I can do just abort() on resource and ignore the ajax response. However, it does not solve the issue. If a browser is clogged if slow responses, which cannot be cancelled, it decreases the performance level. I am contemplating to write my own lightweight version of ngResource with cancelable actions.

psergus avatar Aug 29 '15 03:08 psergus

Correct me if I'm wrong, but I thought that applying a patch for this was relatively easy in Angular's source code?

On Sat, 29 Aug 2015 at 13:34 Sergey Petrenko [email protected] wrote:

yeah, I was playing with the promise as well and following this example https://developer.rackspace.com/blog/cancelling-ajax-requests-in-angularjs-applications/ I can do just abort() on resource and ignore the ajax response. However, it does not solve the issue. If a browser is clogged if slow responses, which cannot be cancelled, it decreases the performance level. I am contemplating to write my own lightweight version of ngResource with cancelable actions.

— Reply to this email directly or view it on GitHub https://github.com/angular/angular.js/issues/9332#issuecomment-135935363 .

kayhadrin avatar Aug 29 '15 04:08 kayhadrin

I see the reason behind copying the config from the Resource to the $http request. (Isolating requests from each other.) But cancellation really needs to be solved. How can you live without it?

I see the arguments for the Resource actions are already Byzantine, but could we add one more optional argument that is a per-request config object for $http? This could be merged with the Resource-level config without copying.

This could be useful in other cases as well. (E.g. decide caching on a per-request basis.) I'd be happy to work on this issue with a little guidance. Thanks!

darabos avatar Oct 08 '15 15:10 darabos