-2

I have the functions below:

(Normally I get the variable msg by doing some query on a XML Object)

function getMsg(callback) {
    var msg = "test"; 
    callback(msg);
}

function msgDone() {
    var message = null;

    getMsg(function(msg) {
       message = msg;
    });

    return message;  //Why is message undefined here?
}

My problem is that I get an undefined on message. I have tested the function getMsg(), and it returns the right value.

How will I make the msgDone to return the message that I get from callback? So that it doesn't return undefined?

Thanks

user1960836
  • 1,732
  • 7
  • 27
  • 47
  • I dont see your problem, it is returning the right value – Nano Jan 26 '15 at 09:02
  • 1
    This might come in handy: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – georg Jan 26 '15 at 09:04

1 Answers1

0

Why is message undefined here?

It won't be, in the code in the question, but my guess is that the real getMsg is an asynchronous operation. That is, when you call it, it starts the process of getting the message but that process completes later, not right away. (For instance, a typical ajax call is like this.)

In that case, the reason message is undefined in the location you marked is that the callback hasn't been called yet, so nothing has ever assigned to message. You can't return the result of an asynchronous call from a function; instead, you have to provide a callback mechanism of your own (simple callbacks, or promises, or similar). E.g.:

function getMsg(callback) {
    // Do something asynchronous...
    // It's done, call the callback
    callback(/*...the data retrieved asynchronously...*/);
}

function msgDone(callback) {
    getMsg(function(msg) {
       // Presumably you do more processing here...
       // ...and then call the callback
       callback(msg);
    });
}

Then, instead of:

var msg = msgDone();
doSomethingWith(msg);
doSomethingElseWith(msg);

you do:

msgDone(function(msg) {
    doSomethingWith(msg);
    doSomethingElseWith(msg);
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875