I'm having a hard time wrapping my mind around jQuery promises. I've created the following snippet to explore jQuery promises; informed by this StackOverflow entry.
let q = [
function () { setTimeout(function () { console.log("a - " + Date.now()); }, 5000); },
function () { setTimeout(function () { console.log("b - " + Date.now()); }, 2500); },
function () { setTimeout(function () { console.log("c - " + Date.now()); }, 0); }
];
function SerialCall(queue) {
var d = $.Deferred().resolve();
while (queue.length > 0) {
d = d.then(queue.shift()); // you don't need the `.done`
}
}
SerialCall(q);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My understanding is that jQuery promises should hold off executing b
and c
while a
is executing and subsequently hold off executing c
while b
is executing.
I was expecting the output to be a, b, c
but I'm getting c, b, a
. Note that I deliberately picked these delays ('a': 5000, 'b': 2500, 'c':0) to illustrate the fact that jQuery promises aren't blocking execution as planned.
What am I missing and how should I alter the code to get the expected behavior?