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!
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.
– Maniero
Are you thinking about
function*
right?– Sergio
I don’t know, as far as I know,
function*
is a generator that creates a "conventional" iterator, right?– Luiz Felipe
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
andfunction*
is a generating function– Sergio
One stream can be seen as asynchronous iterator tb.
– Sergio
I think it’s more connected with protocol than with these constructions that implement protocol.
– Luiz Felipe