How do I make scope destroy event to wait for the promise to resolve ?

414 views
Skip to first unread message

Rahul Tokase

unread,
Apr 10, 2017, 11:30:05 AM4/10/17
to Angular and AngularJS discussion
Hi 

I have written a directive in which on destroy event i need to call some AJAX request and I want my destroy event to wait for the AJAX call to finished.

Here is my code.

scope.$on('$destroy', function() {                   
                     
                        callmethodAsync("").always(function() {
                            // Do some cleanup or logging
                            console.log('inside remember');
                        });
                       
                });

Here i want my destroy method to wait for asyn method execution. How I can achieved that.

Sander Elias

unread,
Apr 10, 2017, 12:38:25 PM4/10/17
to Angular and AngularJS discussion
Hi Rahul,

You can't wait there. The function will get destroyed as soon as it runs to completion.  However, you can take the function you need out of the current event loop, and elevate it to the next using setTimeout. (or, if you need to update anything on screen use the $timer) You can do that like this:

scope.$on('$destroy', function () {
setTimeout(function anonymous() { // When the function eeds to change something in the $scope, use $timer instead
callmethodAsync("").always(function () {
// Do some cleanup or logging
console.log('inside remember');
});
}, 0)
});

Regards
Sander

Reply all
Reply to author
Forward
0 new messages