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

Javascript将元素推送到循环内,不会影响循环外的数组,javascript,arrays,node.js,loops,mongoskin,Javascript,Arrays,Node.js,Loops,Mongoskin,我有一个空数组,我想把项目推到一个循环中。一旦超出循环,阵列将丢失所有信息 var result = []; users.find({}, {username: true, isOnline: true, uniq: true, _id: false}, function(err, cursor) { cursor.each(function(err, item) { result.push(item);

我有一个空数组,我想把项目推到一个循环中。一旦超出循环,阵列将丢失所有信息

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.find和cursor.each函数可能是异步的,因此第二个console.log在cursor执行之前执行。每个和第三个console.log在users.find之前执行。find

看起来您正在使用,您可以使用toArray方法将光标转换为数组,这似乎是你想要的。看看这个:

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


这是您将在node中经常遇到的问题。对于异步代码,其余代码必须放在异步调用的内部。例如,您可以继续处理回调,或者使用承诺。

second console.log语句在用户的回调中执行。find只有当每个函数都是异步的时才会出现这种情况AW04每个函数可能都是异步的,在Javascript中,每个函数都要在数组上迭代同步。游标到底是什么?每个方法是否异步工作?如果没有,那么你对发生的事情的解释就没有意义。我没想到。每个都是异步的。每个都必须是异步的。这种方法从何而来?您应该指定您正在使用的框架/库。这是MongoDB吗?这是MingoDB,在他们的网站上说游标具有each函数。或者,如果您不喜欢CB或Promissions,您可以使用异步/瀑布库
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);