Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The best use case I can think of is in caching AJAX responses. Here's a modified example from <a href="http://rmurphey.com/blog/2010/12/25/deferreds-coming-to-jquery/" rel="noreferrer">Rebecca Murphey's intro post on the topic</a>:</p> <pre><code>var cache = {}; function getData( val ){ // return either the cached value or jqXHR object wrapped Promise return $.when( cache[ val ] || $.ajax('/foo/', { data: { value: val }, dataType: 'json', success: function( resp ){ cache[ val ] = resp; } }) ); } getData('foo').then(function(resp){ // do something with the response, which may // or may not have been retrieved using an // XHR request. }); </code></pre> <p>Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The <code>$.when</code>/<code>.then</code> doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the <code>.then()</code> handler in both cases. <a href="http://api.jquery.com/jQuery.when/" rel="noreferrer"><code>jQuery.when()</code></a> handles a non-Promise/Deferred as a Completed one, immediately executing any <code>.done()</code> or <code>.then()</code> on the chain.</p> <p>Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.</p> <p>Another real world example using the <code>$.when</code> helper:</p> <pre><code>$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) { $(tmpl) // create a jQuery object out of the template .tmpl(data) // compile it .appendTo("#target"); // insert it into the DOM }); </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. 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