I have a long sequence of asynchronous functions to be executed sequentially. So I used promises to create promise queue. Unfortunately on Firefox 25.0.1 on Linux I'm getting too much recursion JavaScript error. It works fine on the same Firefox version on Mac, it works in chrome as well. But I need it working everywhere, including Linux. Can you propose better implementation of executePromiseQueueSync function?
//----------------------------------------------------------------------------------------- function executePromiseQueueSync(queue){ var seed = $.Deferred(); var acc = seed; for (var i = 0; i < queue.length; ++i ) { var promise = queue[i]; acc = acc.then(promise.funct.apply(null, promise.argmnt)); } seed.resolve(); return acc; } //----------------------------------------------------------------------------------------- function someTask(){ var dfd = new jQuery.Deferred(); dfd.notify(); dfd.resolve(); return dfd.promise(); } //----------------------------------------------------------------------------------------- $(function(){ var promisesQueue = [] for(var i = 0; i < 200; ++i){ promisesQueue.push({funct:someTask, argmnt:[]}); } executePromiseQueueSync(promisesQueue).then(function(){alert('done!');}); }); //----------------------------------------------------------------------------------------- JSFiddle example: http://jsfiddle.net/C2YN4/4/
What I have so far (and I'm very open to other propositions and corrections):
function executePromiseQueueSync(queue){ if (queue.length > TRESHOLD){ var i,j; var shortQueue = [] for (i=0,j=queue.length; i<j; i+=TRESHOLD) { temparray = queue.slice(i, i+TRESHOLD); shortQueue.push({funct:executePromiseQueueSync, argmnt:[temparray]}); } return executePromiseQueueSync(shortQueue); } var seed = $.Deferred(); var acc = seed; for (var i = 0; i < queue.length; ++i ) { var promise = queue[i]; acc = acc.then(promise.funct.apply(null, promise.argmnt)); } seed.resolve(); return acc; } So the basic idea is to make a promise tree instead of promise chain. This way we don't go so much deep into stack.
example: http://jsfiddle.net/fMBJK/1/
promise.functget called when it does not return a function? It looks like you are passing promises to.then(), which is invalidsomeTaskis synchronous?