遍历推迟实施项目的无限期阵列 [英] Iterate over indefinite array of deferred items

查看:122
本文介绍了遍历推迟实施项目的无限期阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个很长的列表,其中每个元件都需要一个异步调用获取。我想编写一个API在该列表的顶部,这样,消费者可以简单地称之为下一个()或以其他方式在列表同步迭代。

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);
}

不过,我发现自己绊倒延期调用的语义,我不知道如何摆脱这种硬codeD纹成一个通用的循环:

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,我可以回调做我自己

Presumably, I could do this myself with callbacks

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

但后来我的筹码会得到非常深刻的,这就是为什么我工作deferreds。

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

是否有转向这种异步行为到同步API的秋后算账?

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

推荐答案

您不能有这样的语法,因为它只是进入无限循环忙

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
});

假设的jQuery 1.8 +

Assumes jQuery 1.8+

这篇关于遍历推迟实施项目的无限期阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆