我有一个空数组,我想将项目插入循环内。一旦跳出循环,数组就会丢失所有信息
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
最佳答案
您似乎正在使用 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 处理的事情。对于异步代码,其余代码必须位于异步调用内部。例如,您可以继续处理回调,或使用 Promise。
关于Javascript将元素插入循环内,不会影响循环外的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29976616/