vadimv82
vadimv82

Reputation: 93

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

SOLUTION: Big thanx to Felix. Here is working fiddle

Upvotes: 1

Views: 586

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

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.

Upvotes: 1

Related Questions