向 underscorejs 添加回调函数 _.invoke

add callback function to underscorejs _.invoke

我正在使用 Underscore.js 的 _.invoke() 来销毁一个集合,这里是代码:

 _.invoke(Labels.selectedItems(), 'destroy', {
   error : function (model, response, options) {
     self.isFailed = true; // initialized with false
     utilities.activateNotification("error", "Deleting label failed", response);
   }
 });

如何添加回调函数(或其他机制?)以在所有销毁函数完成后检查 isFailed 的值?

我认为你最好看看 promises 来解决这个问题。

但是这里有一个使用 after 函数的下划线解决方案:

// function will be called after it has been called as many times as there are items
var allDone = _.after(Labels.selectedItems().length, function(){
    console.log('The end');
})

// sample destroy function which calls allDone
var destroy = function(params){
    ....
    allDone();
}