1

hi here is the code im using

function get_last_chat_time(steamid){
if(!db_connect) {
    return 0;
}

chat_db.aggregate(
    [
        {"$match":{"name":"chat-msg",steamid: steamid}},
        { "$sort" : { date : -1 } },
        {"$limit" : 1}
    ]
).toArray(function(err, list){
        if (err) {
            console.log("Error loading history from DB: " + err);
        } else {
            var i = list.length-1;
            var lasttime = Math.floor((new Date() - list[i].date)/1000);
            console.log(Math.floor((new Date() - lasttime)/1000));//this works perfect
           return lasttime;
        }

    });
}
console.log(get_last_chat_time(msg.steamid));// this is undefined

so basicly i want this function to return the value when i call function, when i do console log inside this toArray function its fine out side its not. I just dont understand how to get this to work

  • 1
    Possible duplicate of [How to return value from an asynchronous callback function?](http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – fuyushimoya Nov 05 '15 at 10:46
  • tip: alter `console.log(get_last_chat_time(msg.steamid));` to `get_last_chat_time(msg.steamid);` – BrTkCa Nov 05 '15 at 10:50
  • im not using jquery im using nodejs and mongo db , ive seen your link and its not helping me at all – user2391327 Nov 05 '15 at 10:50
  • @LucasCosta doing that is fine i can get console to give time as i have console log to check its there, it returns nothing at all out side the array function – user2391327 Nov 05 '15 at 10:52

1 Answers1

2

The reason you're getting undefined values is because the toArray() cursor method is asynchronous, and can finish at any time. In your case, it is finishing after you're using console.log(), so the values are undefined when you're accessing them.

To fix this problem, you can only use the values inside the toArray() function's callback. It would look something like this:

function get_last_chat_time(steamid, callback){
    if(!db_connect) {
        return callback(null, 0);
    }

    chat_db.aggregate(
        [
            {"$match":{"name":"chat-msg",steamid: steamid}},
            { "$sort" : { date : -1 } },
            {"$limit" : 1}
        ]
    ).toArray(function(err, list){
            if (err) {
                console.log("Error loading history from DB: " + err);
                return callback(err);
            } 
            var i = list.length-1;
            var lasttime = Math.floor((new Date() - list[i].date)/1000);
            console.log(Math.floor((new Date() - lasttime)/1000));//this works perfect
            return callback(null, lasttime);

        });
}

get_last_chat_time(msg.steamid, function(err, result){
    console.log(result);
})
chridam
  • 100,957
  • 23
  • 236
  • 235