Skip to content

Instantly share code, notes, and snippets.

@sagar-gavhane
Last active June 11, 2018 17:34
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 sagar-gavhane/19a33a64767ef43dce62329ec2bdb6b6 to your computer and use it in GitHub Desktop.
Save sagar-gavhane/19a33a64767ef43dce62329ec2bdb6b6 to your computer and use it in GitHub Desktop.
Generator and Iterators Example
const fetch = require('node-fetch');
const co = require('co');
/*
fetch('https://jsonplaceholder.typicode.com/posts/2')
.then(res => res.json())
.then(res => console.log(title));
*/
// Trying to implement above function using generator and iterator
// Used co library
co(function *(){
const url = 'https://jsonplaceholder.typicode.com/posts/2';
const res = yield fetch(url);
const post = yield res.json();
const title = post.title;
console.log(title);
})
// Implement co library to looking behind the scene how co library work
run(function *() {
const url = 'https://jsonplaceholder.typicode.com/posts/2';
const res = yield fetch(url);
const post = yield res.json();
const title = post.title;
console.log(title);
});
function run(generator){
const iterator = generator();
const iteration = iterator.next();
const promise = iteration.value;
promise
.then(res => iterator.next(res))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment