简体   繁体   中英

Why does this always return “undefined”

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.sendRequest is asynchronous, in which case sendCommand doesn't return anything. The response-handler inside sendCommand is the one that returns something, but that's not the same, as sendCommand returning something. So when you call sendCommand it returns undefined .

Basically, sendCommand invokes the chrome.extension.sendRequest function, and then returns undefined right away, while the chrome.extension.sendRequest function is still running.

There's no real way to make something asynchronous behave synchronously - it's better to restructure your code.

It is most likely because you are performing an ajax call, which is asynchronous by nature. An asynchronous function cannot return a value since there is no way to know when the asynchronous call will complete.

If you are using jQuery, you have two alternative options to get around this problem. If you are using jQuery 1.5 or later, then you can use Deferred Objects. Deferred Objects are a new object that jQuery allows you to use to interact with asynchronous code.

By default, a jquery ajax function (ie $.ajax, $.get, $.post, $.getJSON) returns a Deferred Object, so all you have to do is store your ajax call in a variable and then call available methods listed in the jQuery Deferred Object api. Here is one of the best tutorials I have seen on jQuery Deferred Objects. http://www.erichynds.com/jquery/using-deferreds-in-jquery/

var sendResponse = $.get("/getResponse");

//Somewhere else in your code
sendResponse.success(function(response) {
    return response;
});

The other options is to make your jquery ajax call synchronous. You can do this by setting the async ajax property to false .

$.ajax({
    url: "someURL",
    async: false
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM