0

我正在对 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
             });
4

1 回答 1

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
         });
});
于 2013-06-29T09:38:47.250 回答