Skip to content

Instantly share code, notes, and snippets.

@PetKatt
Created November 13, 2018 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PetKatt/4e0498dc045923e87e6b8fb76e740158 to your computer and use it in GitHub Desktop.
Save PetKatt/4e0498dc045923e87e6b8fb76e740158 to your computer and use it in GitHub Desktop.
generator-function-es6
// 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