What is an asynchronous iterator in Javascript? What is its relation to "for await" loops?

Asked

Viewed 300 times

13

What are asynchronous Javascript iterators? What is their function and what are the differences between the "conventional" iteration protocol?

What is your relationship with for await .. of?

It is possible to use them (asynchronous iterators) in a loop for..of? When it is recommended to use for await .. of instead of for .. of?

  • 3

    It is the will of the JS to become C# :P He copies everything :D Inclusive may be the reason why people abuse lambda in JS. C# has a simple syntax for simple methods that is not lambda, J, it doesn’t, so one uses lambda to simulate, only that pays a price for it.

  • Are you thinking about function* right?

  • I don’t know, as far as I know, function* is a generator that creates a "conventional" iterator, right?

  • 3

    No, it’s a function that can be called multiple times with internal state. It can be used as an iterator but it is not an iterator in the term "process each of these items". My question is why for me asynchronous iterator is for example the for...await and function* is a generating function

  • 2

    One stream can be seen as asynchronous iterator tb.

  • I think it’s more connected with protocol than with these constructions that implement protocol.

Show 1 more comment

1 answer

1

If common makes a scenario which we need to call functions async/await in loops, so in ES2018, the committee of the TC39 presented a new symbol, called Symbol.asyncIterator, as well as a new syntactic construction, called for await .. of. Both help us with the ease to perform function loops async/await.

The main difference between the so-called objects regular Iterators and the asynchronous Iterators is the following:

Iterator object (regular iterator)

The method next of an object iterator returns a value like { value: 'X', done: false }.

For example:

(E) >>> iterator.next()

(S) { value: 'X', done: false }

Asynchronous iterator object (asynchronous iterator)

The method next of an object asynchronous iterator returns a Promise, which will then be resolved into something like:

For example:

(E) >>> iterator.next()

(S) Promise { <fulfilled>: { value: 'X', done: false } }

It is very difficult to answer your question about which iterator to use, because for this, analyses and studies should be made based, but what I can answer you is the following:

As I said above, the committee itself TC39 presented this new iterator (asynchronous) and, if it was created, it is because several studies have been done, so follow documentation and reliable sources like this and do not invent fashion.

A tip I give you to understand more this world of async/await, iterators, symbols, event-oriented programming is in a library which I use a lot in Angular, which is called Rxjs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.