2014-02-12 33 views
0

如何從集合中刪除所有記錄?我試着按照下圖所示做,但1000條記錄中有1000條回調。應該有更好的方法。從一個一個刪除記錄的最後回調的Javascript代碼

dpd.mycollection.get(function(result,error){ 
result.forEach(function(entry) { 
    dpd.mycollection.del(entry.id,function(){}); 
}); 
}) 

我想在最後一條記錄被刪除後才執行一些代碼。我只是不知道該怎麼做。

+1

哪個庫是th如果有的話?承諾在哪裏?或者你想使用承諾,但尚未?在這種情況下,谷歌的「JavaScript承諾」,你會發現很多庫。 –

回答

0

假設Q

Q.ninvoke(dpd.mycollection, "get").then(function(res) { 
    return Q.all(res.map(function(entry) { 
     return Q.ninvoke(dpd.mycollection, "del", entry.id); 
    })); 
}).then(function(dels) { 
    console.log("results of all deletions", dels); 
}, function(err) { 
    console.error("there was an error somewhere", err); 
}); 
0

目前尚不清楚其中的代碼運行,但我會建議使用async.each

function delete_entry (entry, callback) { 
    dpd.mycollection.del(entry.id, callback); 
} 

async.each(entries, delete_entry, function (err) { 
    console.log('finished!'); 
}); 

的方式做到這一點沒有任何圖書館是有個計數器:

var deleted_records = 0; 

entries.forEach(function (entry) { 
    dpd.mycollection.del(entry.id, function() { 
    deleted_records++; 

    //are more records pending to be deleted? 
    if (deleted_records < entries.length) return; 

    //at this point deleted_records is equal to the amount of entries 
    //so we can asume all records have been deleted 
    console.log('finished!'); 
    }); 
}); 
相關問題