Javascript Callback
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
Solution 1:
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 callbackcallback(/*...the data retrieved asynchronously...*/);
}
function msgDone(callback) {
getMsg(function(msg) {
// Presumably you do more processing here...// ...and then call the callbackcallback(msg);
});
}
Then, instead of:
var msg = msgDone();
doSomethingWith(msg);
doSomethingElseWith(msg);
you do:
msgDone(function(msg) {
doSomethingWith(msg);
doSomethingElseWith(msg);
});
Post a Comment for "Javascript Callback"