简体   繁体   中英

Promise in a service cancelling itself

I'm running into a bit of a problem with an Angular (1.4) service. The code is roughly as follows :

    service.retrieveStuffFromServer = function() {
        return httpCallFromServer().then(
            function(data) {
                if (Array.isArray(data)) {
                    return data;
                }
                return [];
            }
        );
    };

I call this function in two distinct controllers. Most of the times, it works as intended, but I'm having problem in those conditions :

  • The HTTP call takes time to return the data
  • Controller A calls the service.
  • Controller B calls the service.
  • The service returns data to controller A
  • The call in the controller B is cancelled. The logic after it never executes

My first guess would be to slightly alter the service, to inform either of the controllers if the service is already busy so I can retry later, but I'm not sure if this is the best solution, so I'm looking for some advice.

Hard to say why it doesn't just work, but presumably something in httpCall() is preventing the same call from being made again before the 1st one completes, and it rejects if that happens. But if you want controller B call to share the response from an active previous call, you could cache the promise:

function myFunction() {
   if (!myFunction.promise) {
     myFunction.promise = httpCall()
         .then(function(result) { 
             myFunction.promise = undefined;
             return ...
         }, function(err) {
             myFunction.promise = undefined;
             throw err;
         });
    }
    return myFunction.promise;
 }

This will cause the same promise from a prior call to be returned as long as the prior call is still unresolved.

Using a property of the function itself as a cache is a convenient way to keep state associated logically with the function itself. You could just use any variable defined outside the scope of myFunction though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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