Node.JS等待从require返回

时间:2015-04-28 21:32:57

标签: javascript node.js

没有哪个地方我能找到答案我正在寻找这个愚蠢的答案8周,请帮助我!!!

我正在创建一个for循环来从数据库服务器获取论坛的主题列表:

for(i=0; i<data.length; i++){
var ownerid = data[i].ownerid,
    info = require(__dirname + '/info.js').run(ownerid, userDataHost, userDataUsername, userDataPassword, userDataName);
    console.log('1)' + info);

    responseOb['latestTopics'] = responseOb['latestTopics'] + '<li><a href="/topic/' + data[i].id +'">' + data[i].name + '</a><span>By ' + info.username + '</li>';

}

但正如你所看到的那样,有一个需要返回一个我在其他responseObject中使用的对象,问题是在使用该脚本中的查询而for循环不会等到他得到一个返回所以info.username是unifined ????????

info.js:

exports.run = function(userid, dataHost, dataUsername, dataPassword, dataName) {
    var info = {username: 'Err'},
        testSQL = require('mysql').createConnection({host: dataHost, user: dataUsername, password: dataPassword, database: dataName}),
        useridEscaped = testSQL.escape(userid);

    testSQL.query('SELECT * FROM `users` WHERE `id`=' + useridEscaped, function(err, data) {
        if (!err){
            if (data.length > 0){
                info['username'] = data[0].username;
                sendBack();
            } else {
                info['username'] = 'undifined';
                sendBack();
            }
        } else {
            sendBack();
        }
    });

    function sendBack(){
        console.log(info);
        return info;
    }

}

请帮帮我!!!!!!!!

0 个答案:

没有答案