Last active
December 9, 2018 18:43
-
-
Save OriginUnknown/882fe07fcd2438bc145116a00551d310 to your computer and use it in GitHub Desktop.
Generators - Understanding the basic mechanics of how raw generators works
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fakeTimeDelay = () => new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(10); | |
}, 1500); | |
}); | |
function* getData() { | |
console.log(`getData() is running`); | |
console.log(`getData() is still running`); | |
console.log(`getData() is about to hit the first yield`); | |
let data = yield fakeTimeDelay(); | |
console.log(`getData() is running after the yield has returned`); | |
console.log(`data value is ${ data * 5 }`); // logs 50 | |
return data + 5; // returns 15 | |
} | |
// Initialises the getData generator | |
let gen = getData(); | |
// gen.next() runs the getData generator method until the first yield is hit. | |
// When this happens in this case, the fakeTimeDelay() method is called and | |
// the results returned to the promise variable | |
let promise = gen.next(); | |
// The value is stored as an iterable object { value: 10, done: false } | |
// It is here that the value could be handled but it MUST BE RETURN by | |
// calling another gen.next() method to RETURN IT BACK to the yield that | |
// called it within the getData generator function if the method is to | |
// contine and the function to complete albeit until the next yield | |
// is hit | |
promise.value.then((num) => { | |
let value = gen.next(num); | |
}); | |
// Final log of getData generator | |
// "getData() is running" | |
// "getData() is still running" | |
// "getData() is about to hit the first yield" | |
// "getData() is running after the yield has returned" | |
// "data value is 50" | |
// 15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment