0

There is no place where i can find the answer i am looking for 8 weeks to this stupid answer, please help me!!!

Well i am creating a for loop to get a topic list for my forum from the database server:

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>';

}

But as you can see there is 1 require wich need to return a object wich i use in de other responseObject, well the problem is that in use a query in that script and the for loop doesn't wait till he gots a return so info.username is undifined????????

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;
    }

}

Please help me!!!!!!!!

Smokegun
  • 81
  • 2
  • 14
  • turn the loop body into a function body, name the function "next", call it from the tail if needed, or done() (not shown) if no more work is left. – dandavis Apr 28 '15 at 21:35
  • There are many things wrong with your code. You have to get a better understand of how functions work. If you have no `return` statement in your function, it will always return `undefined`, that's just how it is. Secondly, you are working with an asynchronous process , so you have to use callbacks or promises. This is a frequently asked topic and there have been written many questions and answers about it. Have a look at http://stackoverflow.com/q/23667086/218196 and http://stackoverflow.com/q/14220321/218196 – Felix Kling Apr 28 '15 at 21:37
  • @FelixKling i still can't figure it out .... can you please give my a fix and tell me what you changed so i can understand what i am doing wrong? i know it now i need a callack but i don't know how to use it with this mysql? – Smokegun May 03 '15 at 12:31

0 Answers0