I'm using a deferred promise to abort a $http
request (like explained in this post).
However, I'm unsure of how I should propagate the abort()
function added at the root level. Everytime I call .then()
on the promise, a new promise (without the abort()
function) is returned.
See my example below. I have a controller calling a service, that in turn calls another service (where the $http
request is made). The example does not work, since promise
in MyController
is not the same as the one that was returned in restService
, and therefore does not have a function called abort()
.
- How can I propagate the
abort()
function so that it is available inMyController
? - Can I return the original promise all the way, and just call
then()
on that (like in the examples at the bottom)?. What happens with thethen()
calls? Are they still invoked "synchronously"?
Controller
app.controller("MyController", function($scope, dataService) {
var promise;
$scope.loadAndAbortData = function () {
promise = dataService.getData().then(updateUI);
};
$scope.abort = function () {
if (promise) {
promise.abort();
}
};
}
DataService
app.service("dataService", function(restService) {
var service = {
getData: function () {
return restService.get().then(function (response) {
var modifiedData = modifyData(response.data);
return modifiedData;
}, function (response) {
handleError(response.data);
$q.reject(response.data);
});
};
};
return service;
}
RestService:
app.service("restService", function($http, $q) {
var service = {
get: function () {
var deferredAbort = $q.defer();
var request = $http.get(url, { timeout: deferredAbort.promise } );
promise.abort = function () {
deferredAbort.resolve();
}
return promise;
};
};
return service;
}
Is this a solution for DataService and MyController?
app.controller("MyController", function($scope, dataService) {
var promise;
$scope.loadAndAbortData = function () {
promise = dataService.getData();
promise.then(updateUI);
};
$scope.abort = function () {
if (promise) {
promise.abort();
}
};
}
app.service("dataService", function(restService) {
var service = {
getData: function () {
var promise = restService.get();
promise.then(function (response) {
var modifiedData = modifyData(response.data);
return modifiedData;
}, function (response) {
handleError(response.data);
$q.reject(response.data);
});
return promise;
};
};
return service;
}