我正在努力学习节点。考虑一下这段代码(基于官方MongoDB Node.js驱动程序)
// Retrieve all the documents in the collection
collection.find().toArray(function(err, documents) {
assert.equal(1, documents.length);
assert.deepEqual([1, 2, 3], documents[0].b);
db.close();
});
我有两个问题:
find
同步还是异步?.toArray
函数调用让我感到困惑,因为通常我会期待一些东西。
collection.find(function(err, results){});
具体来说,我感兴趣的是什么机制允许你在异步函数的结果上调用.toArray
?因为我得到的异步函数很少返回一些东西(我认为除了promises),而是调用传递给它们的回调。有人能用find和.toArray
澄清这种情况吗?
例如,在这个问题的接受答案:How to get a callback on MongoDB collection.find(),你可以看到作者按照我设想的方式调用find
,并在回调函数中收到cursor
。这对我很好,这就是我期望它的工作方式。但链接异步调用find
的结果(如果它是asynch?),与toArray
有点困惑我。
我的猜测是find
返回一个句柄类的东西,此时的数据还没有从DB加载,只有当你调用toArray
实际数据到达时。我对吗?
我承认你,这个案子有点奇怪。这是mongodb-native的v2.2。
首先,find
有two different usages。你可以给出回调函数。但无论如何,它同步返回一个对象。更确切地说,这是一个cursor。传递回调时我们可以期待一种异步机制,但不是这里。
collection.find({ }, function (err, cursor) {
assert(!err);
});
console.log('This happens after collection.find({ }, callback)');
要么
const cursor = collection.find({});
console.log('Also happening after');
另一方面,toArray
是一个异步函数,也有两种不同的用法。这次,返回的对象根据参数而不同。
相当于:
cursor.toArray(function (err, documents) {
assert.equal(1, documents.length);
});
和
cursor.toArray()
.then(documents => {
assert.equal(1, documents.length);
});
在第一次调用中,toArray
返回undefined
,而在第二次调用中,它返回Promise
。