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.
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");
}
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");
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...
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
});
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?
精彩评论