Search code examples
jqueryjquery-deferred

Using jQuery deferred to chain asynchronous functions does not wait for first function to complete


I'm trying to use jQuery (2.1) $.Deferred to chain functions together using then.

I've read through the docs and pretty sure I'm making a stupid mistake somewhere, but I cannot get function second to wait for first to complete.

function first() {
  let deferred = $.Deferred();
  setTimeout(function() { // Any async function.
    $('ul').append('<li>First</li>');
    deferred.resolve();
  }, 500);
  return deferred.promise();
}

function second() {
  let deferred = $.Deferred();
  $('ul').append('<li>Second</li>');
  deferred.resolve();
  return deferred.promise();
}

$(function() {
  $.when(first()).done().then(second());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul>
</ul>

In reality, I want to keep chaining (hence the promise in second as well).

JSFiddle: https://jsfiddle.net/jdb1991/n3aory8c/

How can I make this work correctly?


Solution

  • Remove the brackets () on the second function inside your then() callback. Otherwise you will execute the second function directly and not when the promise resolves.

    $.when(first()).done().then(second);
    

    Working example.