0

Say I have a very long list where each element requires an asynchronous call to fetch. I would like to write an API on top of that list so that a consumer can simply call "next()" or otherwise synchronously iterate over the list.

Ideally I would have something that looks like this:

while ((foo = generator.next()) != null) {
  process(foo);
}

But, I find myself tripping over the semantics of deferred calls, and I don't know how to escape this hard-coded pattern into a generic loop:

$.when(foo).then(process1AndFetch2)
  .then(process2AndFetch3)
  .then(process3AndFetch4)
  ...

Presumably, I could do this myself with callbacks

var callback = function() {
  process();
  fetch(callback);
}
fetch(callback);

But then my stack would get very deep, which is why I was working deferreds.

Are there any usual suspects for turning this kind of asynchronous behavior into a synchronous API?

Chuck
  • 636
  • 3
  • 8
  • 20
  • Take a look [here](http://stackoverflow.com/questions/16384841/chain-ajax-and-execute-it-in-sequence-jquery-deferred/16387812#16387812). The question is phrased differently but my answer should give you some strong clues as to how to build a `.then()` chain dynamically. – Beetroot-Beetroot Dec 02 '13 at 05:45

1 Answers1

1

You can't have such syntax because it would just go into infinite busy loop.

There is a common promise idiom to do this:

var array = [process1AndFetch2, ...]

array.reduce(function(a, b) {
    return a.then(process).then(b);
}, array.shift()()).then(function(){
    //All processed
});

Assumes jQuery 1.8+

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Is there a place to find these common promise idioms? Or common javascript/jquery idioms? – Sumit Dec 02 '13 at 11:16
  • 1
    @Sumit bluebird and Q projects have some promise stuff. https://github.com/kriskowal/q/wiki/Examples-Gallery https://github.com/kriskowal/q#introduction https://github.com/petkaantonov/bluebird#topics – Esailija Dec 02 '13 at 11:39