Created
November 13, 2018 10:20
-
-
Save PetKatt/4e0498dc045923e87e6b8fb76e740158 to your computer and use it in GitHub Desktop.
generator-function-es6
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 fetch = require("node-fetch"); // npm install fetchAPI for Node.js | |
run(function*() { | |
const uri = 'https://jsonplaceholder.typicode.com/todos/1'; | |
const response = yield fetch(uri); // first stop | |
const resJSON = yield response.json(); // second stop | |
console.log(resJSON); | |
}); | |
// take care of the generator function | |
function run(generator) { | |
const iterator = generator(); | |
const iteration = iterator.next(); // runs generator [first YIELD] | |
const promise = iteration.value; | |
promise.then(response => { | |
const iteration2 = iterator.next(response); // runs generator again [second YIELD] | |
const promise2 = iteration2.value; | |
promise2.then(response2 => { | |
iterator.next(response2); | |
}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment