user527154 user527154 - 1 year ago 93
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download