2

The title might be a bit strange, but I'll try to explain.

I do an API call to validate some data. For this I use the following function:

function validateAddress(address) {
    var validationURL = "/api/validateAddress/"+address;

    $.getJSON(validationURL, function(data, textStatus, jqXHR){
        if (textStatus === "success") {
            return data.isValid
        }
    }));
}

// And then in other parts of the code I want to do something like:
if (validateAddress(address)) {
    // do something awesome right here..
}

The problem with this is of course that it is an async call, which causes validateAddress() to not return anything, because it ends before the API call has returned any result.

So how can I actually make validateAddress() return the result of the api call? All tips are welcome!

kramer65
  • 50,427
  • 120
  • 308
  • 488
  • couldnt you call it inside a "success" ? – Felipe Skinner Aug 26 '14 at 13:04
  • The concept you're looking for is **callback-function**, more recently also **[promise](http://promisesaplus.com/)** became more common for this problem. $.getJSON returns a promise, but can also be used with callbacks. – amenthes Aug 26 '14 at 13:07

2 Answers2

1

You have few options:

  • you can either pass parameter to jQuery ajax functions to make the call synchroneous (you can't use getJSON though, you need to use $.ajax directly and pass it async: false)
  • you can pass callback into the validateAddress function as second parameter that you'll call when the request finishes
  • you can return the return value of $.getJSON call from the function validateAddress, since it's a promise, you can attach your code to that with the use of .done() (example of this is here http://api.jquery.com/jQuery.getJSON/#jqxhr-object)
Kamil Szot
  • 17,436
  • 6
  • 62
  • 65
1

How about something like:

function validateAddress(address) {
    var validationURL = "/api/validateAddress/"+address;

    return $.getJSON(validationURL);
}

and then use it like:

validateAddress("myaddress").done(function(response) { 
   // do my stuff here
});
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79