Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign callback data to a variable [duplicate]

Tags:

javascript

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);
like image 919
MrPilot Avatar asked May 09 '14 21:05

MrPilot


People also ask

How do you assign a callback function?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

How do you get the variable from a callback function?

You can pass the exec function a callback. When the exec function determines the username, you invoke the callback with the username. var child = exec(cmd, function(error, stdout, stderr, callback) { var username = stdout. replace('\r\n',''); callback( username ); });

What is callback invocation?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.


1 Answers

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 
like image 146
sfletche Avatar answered Sep 21 '22 22:09

sfletche