简体   繁体   English

如何从angularjs的$ q.defer()promise对象中删除回调

[英]how can I remove a callback from $q.defer() promise object of angularjs

Angularjs $q.defer() promise object receives notify callback, and when we give more than one, it keeps and notify all of them, ie it does not overwrite to older one. Angularjs $q.defer() promise对象接收通知回调,当我们给出多个时,它会保留并通知所有这些,即它不会覆盖旧版本。

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

Then if I want to remove (unregister), for example, callback2 , what should I do? 然后,如果我想删除(取消注册),例如, callback2 ,我该怎么办?

Here is live example: 这是现场的例子:

jsfiddle 的jsfiddle

A quick look at the source for $q shows us that: 快速查看$ q的来源向我们展示:

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;
}

So there is no specific identifier that would point to your anonymous callback in the $$state.pending stack in order to splice it out. 因此,没有特定的标识符指向您在$$state.pending堆栈中的匿名回调以便将其拼接出来。

I haven't personally tried this before but if you wanted to wipe the pending stack, maybe def.$$state.pending = []; 我以前没有亲自试过这个,但是如果你想擦除挂起的堆栈,可能是def.$$state.pending = []; would do the trick. 会做的伎俩。 Then you could simply reassign only the def.then() callbacks you want. 然后你可以简单地重新分配你想要的def.then()回调。

Promises are used to make a sequence of asynchronous processes. Promise用于创建一系列异步进程。 Once a step of this sequence is set, it's not possible (in an elegant way at least) to unset it. 一旦设置了此序列的一个步骤,就不可能(至少以优雅的方式)取消它。

Correct me if I'm wrong, but that's what you are trying to do here: you set a step with the callback2 and then you try to remove that step. 如果我错了,请纠正我,但这就是你要在这里做的事情:你用callback2设置一步,然后你尝试删除那一步。 Instead, I would recommend setting the callback2 only if a certain condition is fulfilled, for example: 相反,我建议仅在满足某个条件时才设置callback2,例如:

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);

Example on jsFidle . 关于jsFidle的示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM