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.

4

2 回答 2

1

正确答案:不要。异步是执行 HTTP 请求的正确方法。但是,在某些情况下,您希望在等待结果时进行阻塞,因此在这些情况下:

使用async参数。

function somefunction() {
    var retVal;
    $.ajax({
         url:    "blabla.php",
         success: function(data) {
                      // modify data here
                      retVal = data;
                  },
         async:   false
    });
    return retVal;
}
于 2013-08-04T19:08:20.180 回答
1

与其从你的函数中返回一些东西,为什么不直接将回调作为参数呢?

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.
}

然后可以像这样使用它:

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

JavaScript 是单线程的,所以这确实是在不阻塞整个脚本的情况下完成此类事情的唯一合理方法。

于 2013-08-05T00:03:25.620 回答