我正在mongoDB上做一个请求,我想为我在数据库中找到的每个对象增加一个变量。
我的问题是我的变量totalSize似乎没有保留它获得的数据,我不知道为什么:/
我认为这是js中的一个闭包问题,但是有人告诉我看看它是不是导致我问题的查询对象的异步特征。
我输了:/
var totalSize = 0;
for (var i = json[0].game.length - 1; i >= 0; i--) {
//When I found a game, I would like to increment his size in totalSize
Game.findOne({
'steamID': json[0].game[i].appID[0]
}, function (err, game) {
if (err) return handleError(err);
if (game) {
//everything is fine here totalSize is the right number
totalSize += game.size;
}
})// where he "forget" my var
//totalSize is still at 0 like I never incremented the variable
console.log(totalSize);
}
res.render('user', {
steamid: steamID,
steamid64: steamID64,
size: totalSize,
content: json
});
答案 0 :(得分:1)
findOne是异步的,在findOne完成之前执行console.log
var totalSize = 0;
for (var i = json[0].game.length - 1; i >= 0; i--) {
//When I found a game, I would like to increment his size in totalSize
Game.findOne({
'steamID': json[0].game[i].appID[0]
}, function (err, game) {
if (err) return handleError(err);
if (game) {
//everything is fine here totalSize is the right number
totalSize += game.size;
}
console.log(totalSize);
})
}
这样做:
function findTotalSize(callback){
var totalSize = 0;
var gameLength = json[0].game.length;
for (var i = gameLength - 1; i >= 0; i--) {
Game.findOne({
'steamID': json[0].game[i].appID[0]
}, function (err, game) {
if (err) return handleError(err);
if (game) {
totalSize += game.size;
}
if(--gameLength == 0)
callback(totalSize);
})
}
}
//use it
findTotalSize(function(totalSize){
res.render('user', {
steamid: steamID,
steamid64: steamID64,
size: totalSize,
content: json
});
});