Ryan Li
Ryan Li

Reputation: 9340

How to block on asynchronous functions in JavaScript

I need to write a function in JavaScript, which returns a state from calling an asynchronous function. However, the caller only receives the value and no callback function is to be provided. I tried something like:

function getState() {
    var ret = null;
    asyncCall("request",
        function() { ret = "foo"; } // callback
    );
    while (ret === null)
        ; // block on the asynchronous call
    return ret;
}

However, the loop is never going to end…

Any ideas? Thank you.

Upvotes: 13

Views: 35282

Answers (5)

Dave Black
Dave Black

Reputation: 8049

Unless I misunderstood your question, you could look at jQuery's ajaxStop() event - http://api.jquery.com/ajaxstop. This blocks until all ajax calls have completed. This obviously requires that all of your async calls be done thru jQuery.

$(document).ajaxStop(function() {
    // do your "ajax dependent" stuff here
});

Upvotes: 1

tomg
tomg

Reputation: 355

I think you're looking for StratifiedJS, http://stratifiedjs.org It allows you to "orchestrate" your async code exactly like you wrote, BEWARE that it "writes" like synchronous code, it will NOT block the rest of your application. You can use it anywhere by loading the apollo js library.

This is how it would look like in Stratified JavaScript:

function getState() {
  waitfor (var ret) {
    // block on the asynchronous call
    asyncCall("request", resume);
  }
  return ret;
}

of course there are modules/libraries that would just make it look like this: http://onilabs.com/modules#http

function getState() {
  return http.get("request");
}

Upvotes: 9

Jean-Bernard Jansen
Jean-Bernard Jansen

Reputation: 7870

what you are trying to do is a synchronous call, so its not a good idea to do it with a function designed for asynchronous call.

You have an answer here : How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

Upvotes: 0

RoToRa
RoToRa

Reputation: 38441

The best would be to put the logic you want to have called into the callback function. Is there any reason why you can't do that?

You could use setInterval to check on the result, but that requires a callback function, too...

Upvotes: 1

Šime Vidas
Šime Vidas

Reputation: 186103

Why not just:

asyncCall("request", function() {
    // here you can inspect the state
});

What's the point of the wrapper function?

Asynchronous functions work this way. If you want to block the execution, then use a synchronous call:

var state = syncCall("request");

Upvotes: 1

Related Questions