Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p><em><code>-&gt;</code> For a more general explanation of async behaviour with different examples, please see</em> <a href="https://stackoverflow.com/q/23667086/218196">Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference</a> </p> <p><em><code>-&gt;</code> If you already understand the problem, skip to the possible solutions below.</em></p> </blockquote> <h1>The problem</h1> <p>The <strong>A</strong> in <a href="https://en.wikipedia.org/wiki/Ajax_(programming)" rel="nofollow noreferrer">Ajax</a> stands for <a href="https://www.merriam-webster.com/dictionary/asynchronous" rel="nofollow noreferrer"><strong>asynchronous</strong></a> . That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, <code>$.ajax</code> returns immediately and the next statement, <code>return result;</code>, is executed before the function you passed as <code>success</code> callback was even called.</p> <p>Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer: </p> <h2>Synchronous</h2> <p>Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer that you needed.</p> <p>The same is happening when you make a function call containing "normal" code:</p> <pre><code>function findItem() { var item; while(item_not_found) { // search } return item; } var item = findItem(); // Do something with item doSomethingElse(); </code></pre> <p>Even though <code>findItem</code> might take a long time to execute, any code coming after <code>var item = findItem();</code> has to <em>wait</em> until the function returns the result.</p> <h2>Asynchronous</h2> <p>You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should <em>call you back</em> on your mobile phone. You hang up, leave the house and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.</p> <p>That's exactly what's happening when you do an Ajax request. </p> <pre><code>findItem(function(item) { // Do something with item }); doSomethingElse(); </code></pre> <p>Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed. To get the response eventually, you provide a function to be called once the response was received, a <em>callback</em> (notice something? <em>call back</em> ?). Any statement coming after that call is executed before the callback is called.</p> <hr> <h1>Solution(s)</h1> <p><strong>Embrace the asynchronous nature of JavaScript!</strong> While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.</p> <p>Why is it bad do you ask?</p> <p>JavaScript runs in the UI thread of the browser and any long running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not. </p> <p>All of this is really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore, the effect will be worse for users with a slow connection.</p> <p>In the following we will look at three different solutions that are all building on top of each other:</p> <ul> <li><strong>Promises with <code>async/await</code></strong> (ES2017+, available in older browsers if you use a transpiler or regenerator)</li> <li><strong>Callbacks</strong> (popular in node)</li> <li><strong>Promises with <code>then()</code></strong> (ES2015+, available in older browsers if you use one of the many promise libraries)</li> </ul> <p><strong>All three are available in current browsers, and node 7+.</strong> </p> <hr> <h2>ES2017+: Promises with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" rel="nofollow noreferrer"><code>async/await</code></a></h2> <p>The new ECMAScript version released in 2017 introduced <em>syntax-level support</em> for asynchronous functions. With the help of <code>async</code> and <code>await</code>, you can write asynchronous in a "synchronous style". Make no mistake though: The code is still asynchronous, but it's easier to read/understand.</p> <p><code>async/await</code> builds on top of promises: an <code>async</code> function always returns a promise. <code>await</code> "unwraps" a promise and either result in the value the promise was resolved with or throws an error if the promise was rejected.</p> <p><strong>Important:</strong> You can only use <code>await</code> inside an <code>async</code> function. That means that at the very top level, you still have to work directly with the promise.</p> <p>You can read more about <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function" rel="nofollow noreferrer"><code>async</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await" rel="nofollow noreferrer"><code>await</code></a> on MDN.</p> <p>Here is an example that builds on top of delay above:</p> <pre><code>// Using 'superagent' which will return a promise. var superagent = require('superagent') // This is isn't declared as `async` because it already returns a promise function delay() { // `delay` returns a promise return new Promise(function(resolve, reject) { // Only `delay` is able to resolve or reject the promise setTimeout(function() { resolve(42); // After 3 seconds, resolve the promise with value 42 }, 3000); }); } async function getAllBooks() { try { // GET a list of book IDs of the current user var bookIDs = await superagent.get('/user/books'); // wait for 3 seconds (just for the sake of this example) await delay(); // GET information about each book return await superagent.get('/books/ids='+JSON.stringify(bookIDs)); } catch(error) { // If any of the awaited promises was rejected, this catch block // would catch the rejection reason return null; } } // Async functions always return a promise getAllBooks() .then(function(books) { console.log(books); }); </code></pre> <p>Newer <a href="https://kangax.github.io/compat-table/es2016plus/#test-async_functions" rel="nofollow noreferrer">browser</a> and <a href="http://node.green/#ES2017-features-async-functions" rel="nofollow noreferrer">node</a> versions support <code>async/await</code>. You can also support older environments by transforming your code to ES5 with the help of <a href="https://github.com/facebook/regenerator" rel="nofollow noreferrer">regenerator</a> (or tools that use regenerator, such as <a href="https://babeljs.io/" rel="nofollow noreferrer">Babel</a>).</p> <hr> <h2>Let functions accept <em>callbacks</em></h2> <p>A callback is simply a function passed to another function. That other function can call the function passed whenever it is ready. In the context of an asynchronous process, the callback will be called whenever the asynchronous process is done. Usually, the result is passed to the callback.</p> <p>In the example of the question, you can make <code>foo</code> accept a callback and use it as <code>success</code> callback. So this</p> <pre><code>var result = foo(); // Code that depends on 'result' </code></pre> <p>becomes</p> <pre><code>foo(function(result) { // Code that depends on 'result' }); </code></pre> <p>Here we defined the function "inline" but you can pass any function reference:</p> <pre><code>function myCallback(result) { // Code that depends on 'result' } foo(myCallback); </code></pre> <p><code>foo</code> itself is defined as follows:</p> <pre><code>function foo(callback) { $.ajax({ // ... success: callback }); } </code></pre> <p><code>callback</code> will refer to the function we pass to <code>foo</code> when we call it and we simply pass it on to <code>success</code>. I.e. once the Ajax request is successful, <code>$.ajax</code> will call <code>callback</code> and pass the response to the callback (which can be referred to with <code>result</code>, since this is how we defined the callback).</p> <p>You can also process the response before passing it to the callback:</p> <pre><code>function foo(callback) { $.ajax({ // ... success: function(response) { // For example, filter the response callback(filtered_response); } }); } </code></pre> <p>It's easier to write code using callbacks than it may seem. After all, JavaScript in the browser is heavily event-driven (DOM events). Receiving the Ajax response is nothing else but an event.<br> Difficulties could arise when you have to work with third-party code, but most problems can be solved by just thinking through the application flow.</p> <hr> <h2>ES2015+: Promises with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="nofollow noreferrer">then()</a></h2> <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="nofollow noreferrer">Promise API</a> is a new feature of ECMAScript 6 (ES2015), but it has good <a href="http://caniuse.com/#feat=promises" rel="nofollow noreferrer" title="caniuse">browser support</a> already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions (e.g. <a href="https://github.com/petkaantonov/bluebird" rel="nofollow noreferrer">bluebird</a>).</p> <p>Promises are containers for <em>future</em> values. When the promise receives the value (it is <em>resolved</em>) or when it is cancelled (<em>rejected</em>), it notifies all of its "listeners" who want to access this value.</p> <p>The advantage over plain callbacks is that they allow you to decouple your code and they are easier to compose.</p> <p>Here is a simple example of using a promise:</p> <pre><code>function delay() { // `delay` returns a promise return new Promise(function(resolve, reject) { // Only `delay` is able to resolve or reject the promise setTimeout(function() { resolve(42); // After 3 seconds, resolve the promise with value 42 }, 3000); }); } delay() .then(function(v) { // `delay` returns a promise console.log(v); // Log the value once it is resolved }) .catch(function(v) { // Or do something else if it is rejected // (it would not happen in this example, since `reject` is not called). }); </code></pre> <p>Applied to our Ajax call we could use promises like this:</p> <pre><code>function ajax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.onload = function() { resolve(this.responseText); }; xhr.onerror = reject; xhr.open('GET', url); xhr.send(); }); } ajax("/echo/json") .then(function(result) { // Code depending on result }) .catch(function() { // An error occurred }); </code></pre> <p>Describing all the advantages that promise offer is beyond the scope of this answer, but if you write new code, you should seriously consider them. They provide a great abstraction and separation of your code.</p> <p>More information about promises: <a href="http://www.html5rocks.com/en/tutorials/es6/promises/" rel="nofollow noreferrer">HTML5 rocks - JavaScript Promises</a></p> <h3>Side note: jQuery's deferred objects</h3> <p><a href="https://stackoverflow.com/questions/4866721/what-are-deferred-objects">Deferred objects</a> are jQuery's custom implementation of promises (before the Promise API was standardized). They behave almost like promises but expose a slightly different API.</p> <p>Every Ajax method of jQuery already returns a "deferred object" (actually a promise of a deferred object) which you can just return from your function:</p> <pre><code>function ajax() { return $.ajax(...); } ajax().done(function(result) { // Code depending on result }).fail(function() { // An error occurred }); </code></pre> <h3>Side note: Promise gotchas</h3> <p>Keep in mind that promises and deferred objects are just <em>containers</em> for a future value, they are not the value itself. For example, suppose you had the following:</p> <pre><code>function checkPassword() { return $.ajax({ url: '/password', data: { username: $('#username').val(), password: $('#password').val() }, type: 'POST', dataType: 'json' }); } if (checkPassword()) { // Tell the user they're logged in } </code></pre> <p>This code misunderstands the above asynchrony issues. Specifically, <code>$.ajax()</code> doesn't freeze the code while it checks the '/password' page on your server - it sends a request to the server and while it waits, immediately returns a jQuery Ajax Deferred object, not the response from the server. That means the <code>if</code> statement is going to always get this Deferred object, treat it as <code>true</code>, and proceed as though the user is logged in. Not good.</p> <p>But the fix is easy:</p> <pre><code>checkPassword() .done(function(r) { if (r) { // Tell the user they're logged in } else { // Tell the user their password was bad } }) .fail(function(x) { // Tell the user something bad happened }); </code></pre> <hr> <h2>Not recommended: Synchronous "Ajax" calls</h2> <p>As I mentioned, some(!) asynchronous operations have synchronous counterparts. I don't advocate their use, but for completeness' sake, here is how you would perform a synchronous call:</p> <h3>Without jQuery</h3> <p>If you directly use a <a href="http://www.w3.org/TR/XMLHttpRequest/" rel="nofollow noreferrer"><code>XMLHTTPRequest</code></a> object, pass <code>false</code> as third argument to <a href="http://www.w3.org/TR/XMLHttpRequest/#the-open%28%29-method" rel="nofollow noreferrer"><code>.open</code></a>.</p> <h3>jQuery</h3> <p>If you use <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow noreferrer">jQuery</a>, you can set the <code>async</code> option to <code>false</code>. Note that this option is <em>deprecated</em> since jQuery 1.8. You can then either still use a <code>success</code> callback or access the <code>responseText</code> property of the <a href="http://api.jquery.com/jQuery.ajax/#jqXHR" rel="nofollow noreferrer">jqXHR object</a>:</p> <pre><code>function foo() { var jqXHR = $.ajax({ //... async: false }); return jqXHR.responseText; } </code></pre> <p>If you use any other jQuery Ajax method, such as <code>$.get</code>, <code>$.getJSON</code>, etc., you have to change it to <code>$.ajax</code> (since you can only pass configuration parameters to <code>$.ajax</code>).</p> <p><strong>Heads up!</strong> It is not possible to make a synchronous <a href="https://stackoverflow.com/questions/2067472/please-explain-jsonp">JSONP</a> request. JSONP by its very nature is always asynchronous (one more reason to not even consider this option).</p>
    singulars
    1. This table or related slice is empty.
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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