How can I remove the callback from $ q.defer () of the angularjs promise object

Angularjs $q.defer() the promise object receives a callback notification, and when we give more than one, it saves and notifies them of all, that is, does not overwrite the older one.

 var def=$q.defer(); def.promise.then(null, null, callback1); def.promise.then(null, null, callback2); 

Then, if I want to delete (unregister), for example, callback2 , what should I do?

Here is a live example:

jsfiddle

+4
source share
2 answers

A quick look at the source for $ q shows us that:

 then: function(onFulfilled, onRejected, progressBack) { var result = new Deferred(); this.$$state.pending = this.$$state.pending || []; this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]); if (this.$$state.status > 0) scheduleProcessQueue(this.$$state); return result.promise; } 

Thus, there is no special identifier that points to your anonymous callback in the $$state.pending stack to combine it.

I personally have not tried this before, but if you want to erase the pending stack, perhaps def.$$state.pending = []; will do the trick. Then you can simply reassign only the def.then() callbacks you want.

+1
source

Promises are used to create a sequence of asynchronous processes. Once the step of this sequence is set, it is impossible (at least elegantly) to turn it off.

Correct me if I am wrong, but this is what you are trying to do here: you set the step with callback2, and then try to delete this step. Instead, I would recommend setting callback2 only if a certain condition is satisfied, for example:

 var notifCallback; if (true) { notifCallback = function(notif) { console.log('notify 1', notif); }; } else { notifCallback = function(notif) { console.log('notify 2', notif); }; } def.promise.then(null, null, notifCallback); 

JsFidle example .

+1
source

All Articles