1

What is purpose of iteratorCount in the following code (from https://deno.land/[email protected]/async/mux_async_iterator.ts)?

#iteratorCount = 0
#yields = []
#throws = []
#signal = deferred()

add () {
  ++this.#iteratorCount
  this.#callIteratorNext(iterator)
}

async #callIteratorNext (iterator) {
  try {
    const { value, done } = await iterator.next()
    if (done) {
      --this.#iteratorCount
    } else {
      this.#yields.push({ iterator, value })
    }
  } catch (e) {
    this.#throws.push(e)
  }
  this.#signal.resolve()
}

async *iterate () {
  while (this.#iteratorCount > 0) {
    await this.#signal

    for (let i = 0; i < this.#yields.length; i++) {
      const { iterator, value } = this.#yields[i]
      yield value

      this.#callIteratorNext(iterator)
    }

    if (this.#throws.length) {
      for (const e of this.#throws) {
        throw e
      }
      this.#throws.length = 0
    }

    this.#yields.length = 0
    this.#signal = deferred()
  }
}

As far as I see, there's nothing to do with iteratorCount if there is no error in all of the iterators added to MuxIterator.

Also, the concept of "not clearing the iteratorCount after an errorhandling" and "loop while (this.iteratorCount > 0)" seems very weird to me.

I've concluded that this kind of stuff is for "manual error handling", in order to make Mux Async Iterator iterates furthermore by adding additional iterators.

Despite that view, I can't think of a situation where iteratorCount go back to zero.

The only way we can decrease the count is to callIteratorNext() and make it done. But, we have to add iterator before it, which makes the count increase.

So, I can't get any role of iteratorCount.

2
  • 1
    "The only way we can decrease the count is to callIteratorNext() and make it done. But, we have to add iterator before it, which makes the count increase." - yes, the count is incremented when you add an iterator, then it loops until the iterator is done, which makes the count decrement. When all iterators are done, the iteratorCount reaches 0 again. Commented Aug 10, 2020 at 12:29
  • I got it. Thank you for helping me. (also editting my question.) I owe you. Commented Aug 10, 2020 at 12:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.