user527154 user527154 - 6 months ago 26
jQuery Question

jQuery promise to simulate synchronous calls of function over array

Let' say I need to make a synchronous upload of files. One after another.
I found this stackoverflow topic. And modified the code:

var arr = ["file1", "file2", "file3"];

var d = $.Deferred().resolve();
while (arr.length > 0) {
d = d.then(uploadFile(arr.shift()));

function uploadFile(file){
var d = $.Deferred();
setTimeout(function(){ console.log("Uploading file:"+file); d.resolve(""); },1000);
return d.promise();

But i still get them all called asynchronously, but with timeout 1000.

Here is fiddle: fiddle

Big thanx to Felix. Here is working fiddle


You have to pass a function to .then. Currently you are calling uploadFile immediately inside the loop and passing a promise to .then instead of a function.

You can do the following without having to use a loop:

d.then(function next() {
  var promise = uploadFile(arr.shift());
  return arr.length === 0 ? promise : promise.then(next);

This uses indirect recursion instead of a loop.