3

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

5
  • 2
    post your code please. Commented May 8, 2017 at 9:14
  • I suggest using setTimeout (Not $timeout to prevent a new digest cycle, and reject this._cancellation outside this.$scope.$evalAsync, Commented May 8, 2017 at 9:44
  • @AlonEitan could you give an example of that suggestion? Commented May 9, 2017 at 10:14
  • 1
    @Javiere I wrote my answer, I hope it's what you need because i'm not 100% sure. Please let me know Commented May 9, 2017 at 16:26
  • 1
    @AlonEitan thank you very much, just needed some adjustments and works perfectly. Commented May 10, 2017 at 10:33

1 Answer 1

3

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'); }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.