我正在结合async.queue
and Cursor.nextObject
迭代游标并对返回的文档执行一些异步工作。
有一个很棒的小包已经可以做到这一点,https://www.npmjs.org/package/mongo-cursor-processing,但不幸的是它没有公开我需要的底层队列。
因此,我尝试自己实现它,但遇到了障碍。有时,Cursor.nextObject
回报null
事实上还有更多文档。
这是我附加到队列中以进行说明的一小段代码片段:
if (this.cursor && this.length() < this.concurrency) {
this.cursor.nextObject(function(err, item) {
console.log(this.name + ': ' + (item ? item._id : '<null>') + ' ' + (err ? err : '<null>'));
if (item) {
this.push(item);
} else {
// delete this.cursor;
}
}.bind(this));
}
控制台日志显示:
... Maybe 100 lines ...
prop-queue: 511abbd59c0d972a3e000119 <none>
prop-queue: 511abbd59c0d972a3e00011d <none>
prop-queue: 511abbd59c0d972a3e000120 <none>
prop-queue: 511abbd59c0d972a3e000122 <none>
prop-queue: <none> <none>
prop-queue: 511abbd59c0d972a3e000125 <none>
prop-queue: 511abbd59c0d972a3e000127 <none>
prop-queue: 511abbd59c0d972a3e000129 <none>
prop-queue: 511abbd59c0d972a3e00012c <none>
... 1000's more lines before the next null ...
有时,<none> <none>
在下一次调用成功之前,该行会重复两次。
真正有趣的部分是当我在 Mongo shell 中执行查询时,之间有一个暂停511abbd59c0d972a3e000122
and 511abbd59c0d972a3e000125
打印到控制台。暂停持续约 0.75 秒,正好在光标命中空文档的位置。我已经在查询中迭代了数千个文档,这是我经历的唯一暂停。此外,检查零点两侧的两份文件并没有发现任何特殊之处。
有什么想法可能导致这两种可能相关的现象吗?
我仍然不确定是什么导致了暂停,但这似乎是罪魁祸首。
暂停期间,Cursor.nextObject
在第一次返回之前被多次调用。其中一些电话正在返回null
。解决方案是确保Cursor.nextObject
永远不会被同时调用。
if (this.cursor && !this.cursor_exec && this.length() < this.concurrency) {
this.cursor_exec = true;
this.cursor.nextObject(function(err, item) {
console.log(this.name + ': ' + (item ? item._id : null) + ' ' + (err ? err : null));
this.cursor_exec = false;
if (item) {
this.push(item);
} else {
delete this.cursor;
}
}.bind(this));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)