【问题标题】:Why do these calls happen in the order they do?为什么这些调用按它们的顺序发生?
【发布时间】:2015-07-08 19:06:57
【问题描述】:

我正在尝试创建一个函数来从 MongoDB 数据库中查询数据并以数组的形式返回所有对象。这是我的代码:

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert')
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/stuff'; //database from which to select is at the end of the path

var myArray = [];
function findStuff(db) {
   var cursor =db.collection('images').find( );
   cursor.each(function(err, doc) {
      assert.equal(err, null);
      if (doc != null) {
         console.dir(doc);
         myArray.push(doc);
         console.log(myArray.length)
      } else {
          db.close();
          console.log("Done with function...");
      }
   });
};

这是我写的一个测试,看看 findStuff 是否正确地将 myArray 设置为集合中的对象数组:

MongoClient.connect(url, function(err, db) {
  findStuff(db);
  console.log("Length of myArray:");
  console.log(myArray.length);
  for (var i = myArray.length - 1; i >= 0; i--) {
    console.log(myArray[i]);
    console.log("Hello"); //This is here to show that the for-loop runs
  };
});

当我使用 Node 运行代码时,我得到以下信息:

Length of myArray:
0
{ _id: { _bsontype: 'ObjectID', id: 'U2eCs/®\tÿ$' },
  id: 1,
  name: 'Tree with sunset 0',
  url: 'http://goo.gl/TgH49m' }
1
{ _id: { _bsontype: 'ObjectID', id: 'U2ÇCs/®\tÿ%' },
  id: 2,
  name: 'Hills n Clouds',
  url: 'http://goo.gl/VXjdSa' }
2
{ _id: { _bsontype: 'ObjectID', id: 'U;\'ó\u0010oiÒ\u001cé' },
  id: 3,
  name: 'Hammock 1',
  url: 'http://goo.gl/CBO3cf' }
3
Done with function...

为什么console.log("Length of MyArray:") 和console.log(myArray.length) 在findStuff 中console.log 的7 次调用之前被调用? for 循环从不做任何事情,因为进入循环时 myArray 的长度为 0。为什么在调用 findStuff 之前会发生 for 循环?或者 findStuff 实际上并没有改变 myArray 的值?无论哪种方式,我都被困住了。怎么回事?

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    问题是db.collection('images').find() 正在异步执行。这意味着它将在下次没有其他运行时排队运行。因此,db.collection('images').find() 在调用其余代码之前还没有机会完成。

    要在检索到数据后运行一些代码,provide a callback

    db.collection('images').find(function(err, results) {
      ...
    });
    

    【讨论】:

    • 做到了!谢谢,迈克。
    猜你喜欢
    • 2014-05-16
    • 2021-11-03
    • 1970-01-01
    • 2015-10-19
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多