1

I basically want to have a function which is GET'ing a page and then returns a result based on that, this leads to the following problem:

All GET methods are using a callback function, meaning that the function will end before the result is there. How do I pause the thread until the callback is fired and then return the result of the callback in my main function?

function someFunction(){

$.get(
    "blabla.php",
    function(data) {
        // This data is supposed to be returned by "someFunction"
    }
)

return //the data we retrieved from 'blabla.php'

}

How would you accomplish this?

EDIT: I know this concept from lua, however I'm not entirely sure if someone would call it "Yielding a function result". Please correct me, if I'm wrong.

Jan Berktold
  • 976
  • 1
  • 11
  • 33

2 Answers2

1

Correct answer: don't. Asynchronous is the correct way to do HTTP requests. However, there are cases when you want to block while waiting on a result, so in those cases:

Use the async parameter.

function somefunction() {
    var retVal;
    $.ajax({
         url:    "blabla.php",
         success: function(data) {
                      // modify data here
                      retVal = data;
                  },
         async:   false
    });
    return retVal;
}
Matt Bryant
  • 4,841
  • 4
  • 31
  • 46
1

Instead of returning something from your function why not just take a callback as an argument?

function someFunction(callback) {
  $.get("blabla.php", function (data) {
    callback(data);
  });
  // Or simply $.get("blabla.php", callback) if the data need not be modified before calling the callback.
}

Which can then be used like so:

someFunction(function (data) {
  alert("Data received!");
});

JavaScript is single-threaded, so this is really the only reasonable way to accomplish something like this without blocking the entire script.

Ethan Lynn
  • 1,009
  • 6
  • 13