从循环中的方法返回变量

时间:2013-04-17 10:24:30

标签: javascript node.js mongodb node-mongodb-native

像这样的东西

var joined = function(arr) {
    var res = [];
    for (var i in arr) {
        var u = DB.getUser(arr[i].user_id, function(user) {
            return user;
        });
        arr[i].user = u;
        res = arr[i];
    }

    return res;
}

我需要从DB.getUser范围获取用户变量。

2 个答案:

答案 0 :(得分:0)

var getJoinedAndDoSomeThingWithThem = function(ids) {
var joined = [];
var i = 0;

var getAUser = function () {
    DB.getUser(ids[i].user_id, function(user) {
        joined.push(user);
        i++;
        if (i == ids.length -1) {
            doSomeThingWithTheResult(joined);
            return;
        }
        getAUser();
    });
}
getAUser();
}

答案 1 :(得分:0)

只是在代码中插入一些注释以帮助理解异步流:

var joined = function(arr) {
    // Timestamp: 0
    var res = [];
    for (var i in arr) {
        // Timestamp: 1
        var u = DB.getUser(arr[i].user_id, function(user) {
            // Timestamp 4 ... length of arr
            // user contains what you are looking for
            // but this is not return to u, because we passed that a long time ago
            return user;
        });
        // u is null or undefined, because DB.getUser returns nothing
        // is a async function, you need wait for the callback
        arr[i].user = u;
        // Timestamp: 2 return useless arr
        res = arr[i];
    }
    // Timestamp: 3 again, return a useless array
    return res;
}

修改

在将所有内容传递给模板之前,您需要这样做,例如:

var joined = function(arr, doneCallback) {
    var res = []
    var count = arr.length;
    for (var i in arr) {
        DB.getUser(arr[i].user_id, function(user) {
            count--;
            res.push(user);
            if (count == 0) {
                doneCallback(res);
            }
        })
    }
}

joined(somedata, function(mydata) {
    render(template, mydata)
});

看看一些流控制库。 (我最喜欢的async