The following code always returns “undefined”
function sendCommand(cmdJson){
chrome.extension.sendRequest(cmdJson, function(response){
return response;
});
}
I’ve also tried this variant with the same result
function sendCommand(cmdJson){
var msg;
chrome.extension.sendRequest(cmdJson, function(response){
msg = response;
});
return msg;
}
If I do an alert(response); instead of return response; I get the expected value.
I’m guessing that
chrome.extension.sendRequestis asynchronous, in which casesendCommanddoesn’t return anything. The response-handler insidesendCommandis the one that returns something, but that’s not the same, assendCommandreturning something. So when you callsendCommandit returnsundefined.Basically,
sendCommandinvokes thechrome.extension.sendRequestfunction, and then returnsundefinedright away, while thechrome.extension.sendRequestfunction is still running.There’s no real way to make something asynchronous behave synchronously – it’s better to restructure your code.