Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are only a couple of things that are asynchronous in JavaScript:</p> <ul> <li>Event listeners</li> <li><code>setTimeout</code></li> <li><code>setInterval</code></li> </ul> <p>AJAX uses event listeners internally.</p> <p>So you do someting like:</p> <pre><code>var xhr = new XMLHTTPRequest(); xhr.addEventlistener('readystatechanged', function () { console.log(xhr.responseText); }); </code></pre> <p>If you're working with a callback your code could look something like this:</p> <pre><code>function do_ajax(url, data, callback) { var xhr = new XMLHTTPRequest(); xhr.open("POST", url); xhr.addEventlistener('readystatechanged', function () { if (xhr.readyState==4 &amp;&amp; xhr.status==200) { callback(xhr.responseText); } }); } do_ajax("service.php", "foo=bar", function (response) { console.log(response); }); </code></pre> <hr> <p>If you have very complex asynchronous processes I recommend taking a look at <a href="http://wiki.commonjs.org/wiki/Promises/A" rel="nofollow">Promises</a>. <a href="http://api.jquery.com/promise/" rel="nofollow">Here is jQuery's take on promises</a>.</p> <p>You can do something like:</p> <pre><code>when(async_process()).then(function (result) { return do_something_asynchronous(result); // &lt;-- the result is a promise }).done(function (result) { // &lt;-- and the resolved value is the input here console.log(result); }); </code></pre> <p>With Promises your code could look like:</p> <pre><code>headlines.getRandom(true).then(function (random_headlines) { return new HeadLine(random_headlines); }).done(headline) { console.log("And presto!", headline); }); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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