views:

72

answers:

3

I have a JavaScript class that has a method:

function someClass() {
    this.someMethod = someClass_someMethod;
}

function someClass_someMethod() {
    // make an AJAX request
}

The problem is that someClass_someMethod() needs to return the value of the AJAX request.

I'm using jQuery's $.getJSON() method to fetch the data. The data needs to be returned but it seems the only way to get the data is through a callback.

How can this be done?

+1  A: 

You could use a non async request, but that ties up the browser whilst the request is in action.

Callback is really the only way, as you need to wait any arbitrary amount of time for the request to either succeed or error.

alex
How can I return a value to the client that is calling `someMethod`, then? Are they going to have to provide a callback?
George Edison
I guess they are :)
George Edison
+1  A: 

Instead of worrying about all the cross browser issues that may arise from writing your AJAX from scratch, I would recommend using an industry standard framework like jQuery to handle your requests as you are currently doing. As Delan Azabani pointed out it is asynchronous and this is a common request amongst people new to asynchronous communication.

function someClass_someMethod(callback) {
    $.getJSON(..., function(data) {
        // process the data here...
        callback(data);
    );
}

you can now do this:

var someClass = new someClass();
someClass.someMethod(function(data) { 
   ... handle your preprocessed data here ...
});

No new concepts in this answer, just providing code examples.

lark
But the data needs to be processed by `someClass` before being returned to the client.
George Edison
Updated to allow you to preprocess the data.
lark
+1  A: 

In this code someClass_someMethod is going to make a non-async request and return the value. So nothing will execute until the request is over, allowing you to return the value.

function someClass() {
    this.someMethod = someClass_someMethod;
}

function someClass_someMethod() {
    var ret = {};
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(data) {
            ret = data;
        },
        async: false
    });
    return ret;
}
BrunoLM