【问题标题】:Issue with Javascript foreach Async behavior [duplicate]Javascript foreach异步行为问题[重复]
【发布时间】:2017-10-22 19:38:22
【问题描述】:

经过一些在线研究,Javascirpt 的 forEach 循环似乎被阻塞,但我的以下代码证明并非如此:

我正在使用 node js mongoDB 驱动程序从我的集合中获取文档,该集合是一个数组(命名文档)

 collectionInstance.find({}, function(err, documents) {
      if (err || !documents) {
        console.log('no documents found in the collection');
      } else {

        console.log('before');

        documents.forEach(function(document) {
          console.log('inside')
        });

        console.log('outside');


      }
    });

我想要什么:

before -> inside, inside, inside .... inside -> outside

它给了我什么:

before -> outside -> inside, inside, inside .... inside 

为什么循环表现得好像它是非阻塞的?

【问题讨论】:

  • documents 只是一个普通的 javascript 数组吗?还是更具异国情调?
  • 见这个:stackoverflow.com/a/11661778/1623249documents 实际上可能是 cursor,而不是数组
  • 如果这实际上是本机驱动程序而不是猫鼬,那么您将通过.find().toArray(err,documents) 获得预期的行为。在.toArray() 返回一个常规数组后,你就有了一个纯 JavaScript .forEach()

标签: javascript node.js mongodb foreach


【解决方案1】:

Javascript 的 Array.prototype.forEach 是同步的(“阻塞”),是的。但是 Mongo 的 Collection.find 返回一个 Cursor,其 .forEach 方法是异步的和基于回调的。 Cursor.forEach 接受一个 second 回调,一旦你遍历所有结果就会调用它:

documents.forEach(function (document) {
  console.log('inside');
}, function () {
  console.log('outside');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-11
    • 2023-04-04
    • 2020-07-26
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2014-11-21
    相关资源
    最近更新 更多