jdborg jdborg - 3 months ago 19
jQuery Question

Using jQuery deferred to chain asynchronous functions

I'm trying to use jQuery

$.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.

HTML

<ul>

</ul>


JS (jQuery 2.1)

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());
})


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

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

Any ideas? Thanks in advanced.

Answer

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.