他可能指的是序列助手,在下一个回调中运行一个任务意味着链将同步运行。
这是我用于将大量数据插入 Mongo 集合的生成器的示例。这会生成要并行执行的操作序列。在这种情况下,通过使用回调方法链接它们来执行一百万次插入并不是很实用。所以这就是为什么我使用像下面这样的生成器/序列助手。
var Inserter = function (collection) {
this.collection = collection;
this.data = [];
this.maxThreads = 30;
this.currentThreads = 0;
this.batchSize = 1000;
this.queue = 0;
this.inserted = 0;
this.startTime = Date.now();
};
Inserter.prototype.add = function(data) {
this.data.push(data);
};
Inserter.prototype.insert = function(force) {
var that = this;
if (this.data.length >= this.batchSize || force) {
if (this.currentThreads >= this.maxThreads) {
this.queue++;
return;
}
this.currentThreads++;
console.log('Threads: ' + this.currentThreads);
this.collection.insert(this.data.splice(0, this.batchSize), {safe:true}, function() {
that.inserted += that.batchSize;
var currentTime = Date.now();
var workTime = Math.round((currentTime - that.startTime) / 1000)
console.log('Speed: ' + that.inserted / workTime + ' per sec');
that.currentThreads--;
if (that.queue > 0) {
that.queue--;
that.insert();
}
});
}
};