jQuery - how to register a callback for an asynchronous function?

javascript, jquery

Solution

You cannot "return" from `$.get`, it doesn't work that way. What you want to do is pass a callback to `checkMsgs` and call it when `$.get` is done.

function checkMsgs(t1, t2, callback) {
    $.get("http://www.mySite.com/web/test.php", {
        "t1": t1,
        "t2": t2
    }, function (data) {
        // do whatever...
        $.isFunction(callback) && callback(data);
    });
}

Then you call `checkMsgs` like this:

checkMsgs('a', 'b', function(data){
    console.log(data);
});

Problem

I am a jQuery newbie. I have a core js file which will not be visible to my user. I have the following function inside it that makes a server request - ``` function checkMsgs(t1,t2) { // poll the url // return the results $.get("http://www.mySite.com/web/test.php", { "t1" : t1, "t2" : t2 }, function(data) { return data; }); } ``` Now, I want to call this function, without blocking the thread i.e., asynchronously. How do I make a function call after it returns from this method, but without blocking anything?

Original source