【问题标题】:Angular: how to destroy a promiseAngular:如何破坏承诺
【发布时间】:2016-11-07 00:46:59
【问题描述】:

In my word-cloud application I have 2 directives, a word cloud directive and table directive that when a word in the word cloud is selected, it notify to the table so the table will also select the correspond word. word-cloud 和 table 通过服务中的 promise 进行通信,我想销毁 promise:

服务代码:

this.selectedDefferd = $q.defer(); 

this.selectedPromise = this.selectedDefferd.promise;

   notifySelect(id)
   {
        this.selectedDefferd.notify({newData: this.data[id]});
    }

 setSelect(callBack) {
    this.selectedPromise.then(null, null, callBack);
}

词云指令代码:

d3.select(this).on("click", function (d) {
...
ctrl.wordService.notifySelect(d.id);
}

表格指令

var selectCallback = $(".selected");

wordService.setSelect(selectCallback);

提前致谢,

哈雷尔

【问题讨论】:

  • 你所说的“破坏”到底是什么意思?你为什么想要那个,它有什么好处?
  • $element.on("$destroy", function () { console.log("wordCloud controllerdestroy"); }) 为了避免内存泄漏
  • 你可以this.selectedDefferd = null,但我认为否则也不会导致内存泄漏。
  • notify 是一个糟糕的 API,我建议不要这样做。我个人会为此使用事件发射器。 Promise 中的通知不健全,也不能很好地工作。
  • @BenjaminGruenbaum “事件发射器”是什么意思?

标签: javascript angularjs promise destroy


【解决方案1】:

使用reject() 你可以拒​​绝一个promise

this.selectedDefferd.reject('Rejected!');

promise 的第二个参数是拒绝。

promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-02
    • 2020-10-03
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多