Iterate over indefinite array of deferred items

做~自己de王妃 提交于 2019-12-18 07:22:48

问题


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?


回答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+



来源:https://stackoverflow.com/questions/20308641/iterate-over-indefinite-array-of-deferred-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!