Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

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.

Answer*

Draft saved
Draft discarded
Cancel
3
  • It's something like a library since I am working across several platforms. And the rest of the code needs to wait for this special piece of information. No synchronous substitution is provided. Commented Dec 3, 2010 at 13:36
  • 2
    @Šime: So you mean asynchronous calls could infect all other code calling it? I just want to know if there is a way to block on these async calls. Commented Dec 3, 2010 at 13:40
  • 1
    @ryanli: There is no way to block async call unless you A: rewrite the async call to be synchronous or B: rewrite your code to work in an asynchronous environment. In javascript it is considered best practice to do B since 1999. Commented Dec 3, 2010 at 13:50

lang-js

AltStyle によって変換されたページ (->オリジナル) /