返回介绍

AsyncSequence

发布于 2019-05-31 13:13:12 字数 2740 浏览 1119 评论 0 收藏 0

An AsyncSequence iterates over its elements asynchronously when #each is called.

You get an AsyncSequence by calling Sequence#async on any sequence. Note that some sequence types may not support asynchronous iteration.

Returning values

Because of its asynchronous nature, an AsyncSequence cannot be used in the same way as other sequences for functions that return values directly (e.g., reduce, max, any, even toArray).

Instead, these methods return an AsyncHandle whose onComplete method accepts a callback that will be called with the final result once iteration has finished.

Defining custom asynchronous sequences

There are plenty of ways to define an asynchronous sequence. Here's one.

  1. First, implement an Iterator. This is an object whose prototype has the methods Iterator#moveNext (which returns a boolean) and current (which returns the current value).
  2. Next, create a simple wrapper that inherits from AsyncSequence, whose getIterator function returns an instance of the iterator type you just defined.

The default implementation for #each on an AsyncSequence is to create an iterator and then asynchronously call Iterator#moveNext (using setImmediate, if available, otherwise setTimeout) until the iterator can't move ahead any more.

Signature

function AsyncSequence(parent, interval) { /*...*/ }
function AsyncSequence(parent, interval) {
  if (parent instanceof AsyncSequence) {
throw new Error("Sequence is already asynchronous!");
  }

  this.parent         = parent;
  this.interval       = interval;
  this.onNextCallback = getOnNextCallback(interval);
  this.cancelCallback = getCancelCallback(interval);
}
NameType(s)Description
parentSequence

A Sequence to wrap, to expose asynchronous iteration.

intervalnumber?

How many milliseconds should elapse between each element when iterating over this sequence. Note that this interval applies even to the first value in the sequence; i.e., when calling each(), this much time will elapse before the first element is iterated.

If this argument is omitted, asynchronous iteration will be executed
as fast as possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文