Javascript 将元素推入循环内,不会影响循环外的数组

Javascript Pushing elements inside a loop, doesn't affect the array outside the loop

我有一个空数组,我想在一个循环中将项目推入其中。一旦在循环之外,数组就会丢失所有信息

var result = [];
        users.find({}, {username: true, isOnline: true, uniq: true, _id: false}, function(err, cursor) {
            cursor.each(function(err, item) {
                result.push(item);
                console.log(result); //every iteration the array shows fine
            });

            console.log(result); //array is empty
        });

        console.log(result); //array is empty

这可能是因为 users.findcursor.each 函数可能是异步的,因此您的第二个 console.log 在 cursor.each 和第三个 [=16] 执行之前执行=] 在 users.find

之前执行

你好像用的是Mongoskin,你可以用toArray的方法把光标转成Array,好像是你想要的。 看看这个:

http://www.hacksparrow.com/mongoskin-tutorial-with-examples.html

db.collection('stuff').find().toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
});

因此您的代码将如下所示:

var result = [];
        users.find({}, {username: true, isOnline: true, uniq: true, _id: false})
        .toArray(function(err, cursor) {
            // cursor is now an array. forEach is sync.
            cursor.forEach(function(item) {
                result.push(item);
                console.log(result); //every iteration the array shows fine
            });

            console.log(result); // Should not be empty now
            // Add more code in here, if you want to do something with
            // the result array
        });
        // Still empty, because find is async.
        // Your code should go inside of the users.find call
        // and not here
        console.log(result);

这是您在使用 node.js 时会经常处理的事情。对于异步代码,其余代码必须放在异步调用中。例如,您可以继续处理回调或使用 Promises。