In my AjaxPromiseService.js factory, I have been trying to incorporate a timeout mechanism into promise calls (usually $http.get/post calls to remote services). The way I am currently doing is to create a race between a $timeout event and the actual promise calls. Example code as following (code from my AjaxPromiseService.js factory in AngularJS): also available in this plnkr
var timeoutObj = {"isTimeout": true};
function timeoutPromise(deferredObj) {
$timeout(function() {
console.log("promise timeout");
deferredObj.resolve(timeoutObj);
}, timeoutLimit); // timeoutLimit is in milisecond
}
//promise calls (e.g. $http.get())
function getDummyData(milisec) {
var data = {"data" : "dummy data from ajax!"};
var deferred = $q.defer();
timeoutPromise(deferred); //start the race to see who resolves first
//use $timeout to mimick an AJAX call
$timeout(function() {
deferred.resolve(data);
$timeout.cancel(timeoutPromise(deferred)); //not working, how to cancel the race here?
}, milisec); //
return deferred.promise;
} //getDummyData
This seems working, if getDummyData() is not resolved within the specified duration, the timeoutPromise() will return the useful flag so I can let the AJAX calls fail gracefully. Both timeoutPromise() and getDummyData() will resolve eventually in a sequential order, however, I would like to cancel timeoutPromise() if getDummyData() is reslolved first. I was wondering how to do this?