Part 4: async generators
This is a continuation of Understanding Generators series. In previous articles I have discussed what is happening under the hood when we invoke a generator function as well how to pass data to a generator function dynamically.
Take a look at this code snippet.
function doWhenDataReceived(value) { returnNextElement.next()}function* createFlow() { const data = yield fetch(‘https://...'); console.log(data);}const returnNextElement = createFlow();const futureData = returnNextElement.next();futureData.then(doWhenDataReceived);
And this is a diagram that explains what is happening under the hood when JS runs this code.
There is a great explanation for points 1,2,3,6 in my previous articles of this series. However, it is worth mentioning that when we call fetch in step 4, two things are happening under the hood.
Get Sveta Buben’s stories in your inbox
Join Medium for free to get updates from this writer.
1) In JS it returns a promise object with properties ( the one we are interested in) value and onFulfillment. value is undefined at the beginning, but it is populated with a value once a promise is resolved (here at 200ms promise is resolved with value ‘hi’). onFulfillment in an empty array at the beginning, but method .then adds a function (here doWhenDataReceived) to the onFulfillment that will be invoked once value property is assigned to some value (here at 200ms promise is resolved with value ‘hi’ and assign it to futureData.value) ( I am omitting a process of Event Loop and Microtask queue here for brevity)
2) Also, it speaks to Web Browser API feature XmlHttpRequest, which speaks to a server and returned value assigned to the value property of futureData object.
Great, leave your comment if you found this a bit confusing for you or share was it helpful for you 💖
Next article will talk about async await
Resources:
☛ https://frontendmasters.com/courses/javascript-new-hard-parts/ — by Will Sentance







