Reputation: 1651
I have a method which is using evalAsync and I would like to set a maximum waiting time for the promise to be resolved, if the waiting time reaches the max timeout then the promise will be resolved and returned empty. Any ideas about how to accomplish this?
It's being hard to find solutions as every search with the terms evalasync and timeout, "pollutes" the results with $timeout.
if (angular.isFunction(this.search)) {
this.cancellation = this.$q.defer<void>();
this.$scope.$evalAsync(() => {
const searchArgs= {
value: this.value,
cancellation: this.cancellation.promise
};
const result = this.search(args);
});
}
};
Thanks
Upvotes: 3
Views: 699
Reputation: 12025
As described in the docs - "The $evalAsync
makes no guarantees as to when the expression
will be executed".
So if you want to resolve a promise after X milliseconds, then you can combine it with setTimeout
(Not $timeout
, because we don't want to trigger a digest cycle).
This is my suggestion, I will only show you the basic logic because I'm not sure if I understand your issue correctly, so please let me know so I can change my answer or delete it if it's not helpful at all:
var deferred = $q.defer();
// Save the timeout ID so we can know what to do with our promise
var timeout = setTimeout(function() {
// Clear the timeout ID and reject the promise after 3 seconds
timeout = null;
deferred.reject();
}, 3000);
$scope.$evalAsync(function() {
if( !timeout ) {
// Too late, the promise was rejected inside 'setTimeout'
return;
}
// Prevent 'setTimeout' from being executed by clearing its ID
clearTimeout(timeout);
deferred.resolve({busy: false}); // Of course, you can pass any other value here
});
deferred.promise.then(
function( data ) { console.log('resolved'); },
function() { console.log('rejected'); }
);
Upvotes: 3