tuxmobil tuxmobil - 8 months ago 164
Javascript Question

how to cancel a promise with $resource in angularjs in 1.5

I'm using angular 1.5.7 and would like to cancel a delete on a resource if it takes time. I'm using a MEAN stack and sometimes I see the delete on my resource seen as pending (is it mongo which is slow ?).
Below is the factory and the snippet from the controller where I call the delete:
* the factory:

.factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
'update': {
method: 'PUT'
'delete': {
method: 'DELETE'

  • the snippet from the controller:

    $scope.delete = function (address, addressesList) {


    console.log('[ModeratorsCtrl] Deleting:' + address.name);
    console.log('[ModeratorsCtrl] ' + addressesList.length);
    addressesFactory.delete({id: address._id}).$promise.then(
    function (response) {
    console.log('[ModeratorsCtrl] Address deleted successfully');
    function (response) {
    var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;


I saw this post How to cancel $resource requests and read this about cancelling requests: https://docs.angularjs.org/api/ngResource/service/$resource#! with $cancelRequest() but I'm a bit confused.
Can anyone give me the best practices on how I can cancel a promise in my implementation ?


lets say your resource is Users, to cancel the request, you should name your action e.g

var request = Users.query();

at this point ```request is a promise. you can simply do a,


to cancel.