0

I'm trying to assign a function's return value to a variable, using this stackOverflow article as a template. Here's my code:

var host = getHostName(djId, function(name) {
    return name;
});
console.log(host);    // undefined :(


function getHostName(id, cb) {
    var reply;
    userColl.findById(id, function (err, dj) {
        if (err) {
            reply = "db error";
        } else {
            reply = dj.firstName + ' ' + dj.lastName;
        }
        console.log(reply + ' reply');    // working as expected!
        cb(reply);
    });
}

the console.log(reply) is working as expected but host is still undefined when i try t call the function. what gives?

wkd
  • 231
  • 1
  • 5
  • 16

1 Answers1

1

Because it's the result of getHostName which itself doesn't return anything. It seems like an asynchronous function, so if you need to do something with the value, you have to put it inside of the callback.

The inner function (callback) is executed asynchronously so when it runs, the execution of getHostName is already finished. And that's why the inner function can't return anything to the variable. All code, which will do something with the name, has to be inside of the callback.

var host = getHostName(djId, function(name) {
    console.log(name); // Here you go
    anotherFn(name); // Here you can have the rest of your code which needs the name
});
Razem
  • 1,421
  • 11
  • 14
  • thanks for the reply. i'm new to async, server-side, and pure js (basically anything but jquery). could you give me an example of what you're talking about? – wkd Jul 25 '14 at 18:48
  • @wkd Okay, I made an edit with a better explanation. – Razem Jul 25 '14 at 20:10
  • thanks - modifying to fit your example is working with console.log, but the point of this function is to return a string that can be assigned to a variable and used throughout. here's what i want to do: var host; getHostName(djId, function(name) { host = name; }); console.log(host); <-- undefined still!! – wkd Jul 25 '14 at 20:37
  • 1
    @wkd And as I said you can't do that because the callback is run asynchronously. So just move the code which needs the host/name variable to the callback. Is it really such a problem? – Razem Jul 25 '14 at 21:12