JavaScript - generators, iterators, asynchronity and Promises
Iteration protocols: iterator
and iterable
ES6 specifies two protocols. They are iteration protocols: iterable
protocol i iterator
protocol.
Iterable is an object which has it's own method @@iterator
under the key Symbol.iterator
.
Iterator is a function which returns next
function which returns an object with keys done
and value
.
An object is an iterator when it implements a next()
method with the following semantics:
var myIterator = {
next: function() {
// ...
return {
done: ...,
value: ...
}
}
[Symbol.iterator]: function() { return this }
};
How to iterate over an object?
To iterate over values of an object, it has to have a special method @@iterator
, which should be defined under [Symbol.iterator]
key.
String
, Array
, TypedArray
, Map
and Set
are all built-in iterables, because each of their prototype objects implements an @@iterator
method.
Generators
Generator object behave like a iterator, it is an object which has it's own method next
.
Generator function is a function which returns generator object.
For me, generator function it is just a syntactic sugar, a function which returns an iterator
with a next
key. Instead of returning next
, we return an values of iterator
using yield
.
var myIterable = {};
myIterable[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
[...myIterable]; // [1, 2, 3]
Promises
Promise.all()
method
Only parameter of this method is iterable which means an array for example. This method is processing all promises in parallel and waits until they are all solved.
Processing Promises sequentially
const iterable = [fn1, fn2, fn3, …]
iterable.reduce((p, fn) => p.then(fn), Promise.resolve())
// or
for (let i = 0; i < iterable.length; i++) {
await iterable[i]()
}
// or
for (value of iterable) {
await value()
}
More information about processing them sequentially can be find here.