如何删除集合中的所有记录?我尝试如下所示,但对于1000条记录,有1000个回调。应该有更好的方法。
dpd.mycollection.get(function(result,error){
result.forEach(function(entry) {
dpd.mycollection.del(entry.id,function(){});
});
})
我想在删除最后一条记录后才执行一些代码。我只是不知道该怎么做。
答案 0 :(得分: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);
});
答案 1 :(得分: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!');
});
});