Understanding generator
Where it comes from
From MDN:
The Generator object is returned by a generator function and it conforms to both the
iterable
protocol and theiterator
protocol.
This object cannot be instantiated directly. Instead, a
Generator
instance can be returned from agenerator function
:
1 | function* generator() { |
How it runs
It pauses at yield
keyword and can resume from there.
If there is:
1 | y = yield 1 |
When calling gen.next(2)
, generator will yield 1
and pause before the y =
assigning. And then when calling gen.next()
, generator will assign y = 2
and yield 2.
async
await
are based on generator
Definition
1 | function _asyncToGenerator(fn) { |
Usage
1 | const asyncFunc = _asyncToGenerator(function* () { |
Same output as:
1 | const asyncFunc = async () => { |
An interesting observation on promise being flattened
I noticed that if instead of returning [a, b, c]
in the end, I return another promise that wraps multiple layers of promise, resolves to [a,b,c]
, the .then
will still resolve to [a, b, c]
.
This is because Promise.resolve()
flattens the promise:
This function flattens nested layers of promise-like objects (e.g. a promise that resolves to a promise that resolves to something) into a single layer.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve