Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript/jQuery - is it possible to encapsulate and return the result of an asynchronously executed function?
    text
    copied!<p>I know this question has been asked many times in many different ways, but I am still having trouble identifying a good solution to the following problem. </p> <p>How can I wait for the callback of this asynchronously-executed inner function to complete prior to returning from the outer function? </p> <pre><code>function outer() { var result = false; var innerAsynch = function() { result = true; } setTimeout(innerAsynch, 1000); waitForInnerAsynch(); //blocking return result; //true } </code></pre> <p>1) I am well aware that this is bad practice for 99.999% of use cases, so please don't tell me that it shouldn't be done! </p> <p>2) Please feel free to completely restructure this code... my only requirement is that outer() returns something which blocks the browser until innerAsynch() is done and passes the following test:</p> <pre><code> if(outer()) { //1 second later.... yippee! } </code></pre> <p>Also I am using jQuery, but I would prefer not to use a plugin unless it really makes sense to do so. Thanks!</p> <p><strong>Update</strong></p> <p>I want to reiterate that my goal is to fully encapsulate the asynchronous execution within the synchronous call to outer() without arguments. </p> <p>In other words, this should work:</p> <pre><code>&lt;a href="something" onclick="return outer()"&gt;A very slow link&lt;/a&gt; </code></pre> <p>Perhaps this is not actually possible, in which case I am fine using callbacks, but I want to develop a better understanding of why that is the case.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload