7

I've been trying to figure out how to set the value from a callback to a variable so that I can call the variable and access the data rather than having to place all my code inside the callback function. I posted two examples one which works, and the second which does work and returns undefined. How can I make it so that the second example works?

Here is where I get my data.

var chromeApi = {
    msg: function (callbacks) {
        chrome.runtime.sendMessage({type: "settings"}, callbacks);
    }
};

When I access the data from chromeApi this way it works fine.

chromeApi.msg(function (response) {
    console.log(response);
});

But I want to access it this way I get undefined. How can I make my code work to use this method?

var test = chromeApi.msg(function (response) {
    return response;
});
console.log(test);
MrPilot
  • 163
  • 2
  • 3
  • 9

1 Answers1

13

Welcome to the world of asynchronous programming. :)

If you want to assign response to test, you CAN do so within the asynchronous callback:

chromeApi.msg(function (response) {
    test = response;
});
console.log(test);

BUT...because the callback is asynchronous (meaning we don't know when that assignment statement will actually execute) we won't know whether or not

test = response;

is executed before

console.log(test)

until run-time.

My guess from the above code is that console.log(test) will get executed before test = response (however, that same order of execution may not happen every time as asynchronous programming exhibits non-deterministic behavior).

Depending on what you want to do with the response value will dictate whether or not it needs to be done within the callback.

This is guaranteed to work

chromeApi.msg(function (response) {
    test = response;
    // do something with test
});

this is not

chromeApi.msg(function (response) {
    test = response;
});
//do something with test 
sfletche
  • 47,248
  • 30
  • 103
  • 119