迭代Promise迭代器的非递归方法 [英] Non-recursive method to iterate over Promise iterator

查看:70
本文介绍了迭代Promise迭代器的非递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发了一个客户端库,它公开了一个名为 iterator()的方法。此方法返回使用 require('promise')库创建的Promise实例,该库使用迭代器对象完成。

I've developed a client library that exposes a method called iterator(). This method returns a Promise instance created using require('promise') library, which is completed with an iterator object.

此对象包含一个名为 next()的方法,它返回一个Promise,它使用如下复杂对象完成: {done:[true | false],key:_,value:_}

This object contains a method called next() which returns a Promise which is completed with a complex object like this: {done: [true|false], key: _, value: _}

虽然 iterator()可能会预先获取一些元素, next()需要返回一个Promise,以防它导致远程调用。

Although iterator() might pre-fetch some elements, next() needs to return a Promise in case it results in a remote call.

现在,假设用户想要迭代所有元素,直到 next()返回的Promise返回一个包含 done的对象:true

Now, say a user wants to iterate over all elements until the Promise returned by next() returns an object containing done: true.

我已经设法使用以下递归方法实现了这一点(我最初在这个答案):

I've managed to achieve this using the following recursive method (I originally found this solution in this answer):

var iterate = client.iterator();

iterateTeams.then(function(it) {

  function loop(promise, fn) {
    // Simple recursive loop over iterator's next() call
    return promise.then(fn).then(function (entry) {
      return !entry.done ? loop(it.next(), fn) : entry;
    });
  }

  return loop(it.next(), function (entry) {
    console.log('entry is: ' + entry);
    return entry;
  });

});

问题是,是否有可能,使用 require('promise' )库,构建一个非递归的解决方案?我对非递归方法感兴趣的原因是,如果要迭代的条目数太大,就要避免爆炸。

The question is, would it be possible, using require('promise') library, to build a non-recursive solution? The reason I'm interested in a non-recursive method is to avoid blowing up if the number of entries to iterate over is too big.

干杯,
加尔德

Cheers, Galder

推荐答案


我对非递归方法感兴趣的原因是为了避免炸毁如果迭代的条目数太大

The reason I'm interested in a non-recursive method is to avoid blowing up if the number of entries to iterate over is too big

不要害怕。异步递归(有时称为伪递归)不会增加调用堆栈,它很像尾递归。你永远不会得到一个stackoverflow异常。

Don't fear. Asynchronous "recursion" (sometimes dubbed pseudo-recursion) does not grow the call stack, it's much like tail recursion. You won't ever get a stackoverflow exception.

如果合理地实现了promise库,这甚至不会增加内存 - 参见在javascript中递归建立一个承诺链 - 内存注意事项以获取详细信息。

And if the promise library is implemented reasonably, this should not even grow the memory - see Building a promise chain recursively in javascript - memory considerations for details.

这篇关于迭代Promise迭代器的非递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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