A
A
aarifkhamdi2019-08-20 16:22:44
JavaScript
aarifkhamdi, 2019-08-20 16:22:44

Is it possible to reuse asyncIterator in JavaScript?

There is the following code snippet. Tell me, please, is it doomed to failure or am I not catching up with something?
I'm confused about reusing exactly the same iterator in two (for ... of ...). Is it possible to do so? The iterator is a one-time iterator, isn't it?
Can this be made to work?
PS: if replace this

for await (const person of { [Symbol.asyncIterator]() { return iterator; } }) {
on this , then everything works out successfully. I'm wondering if it can work exactly in the form in which I got it
for await (const person of target) {
const iterator = target[Symbol.asyncIterator]();

const iterated = [];
for await (const person of { [Symbol.asyncIterator]() { return iterator; } }) {
    iterated.push(person);
}

t.same(iterated, [],
    'iterates sucessfully over empty collection');

const toAdd = [1, 2, 3];
await target.addToTarget(toAdd);

for await (const person of { [Symbol.asyncIterator]() { return iterator; } }) {
    iterated.push(person);
}

t.same(iterated, toAdd,
    'iterates sucessfully after adding to collection (iterator does not invalidate)');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-08-20
@aarifkhamdi

why disposable? https://jsfiddle.net/melchiorio/oz12tg3k/
I don't understand the point of creating an empty object with an iterator from another object. Does an iterator create properties on an object? If yes, then why are they not used in the future, if not, then why put this data in properties?
upd: I
reproduced your example https://jsfiddle.net/melchiorio/n5awv1bd/1/, it looks like such a tricky way is made to have just a one-time iterator, adding elements through addToTargetand running it again, it only goes through new values ​​apparently.
And it works the same for you, because the first launch is empty.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question