Last active
June 11, 2018 17:34
-
-
Save sagar-gavhane/19a33a64767ef43dce62329ec2bdb6b6 to your computer and use it in GitHub Desktop.
Generator and Iterators Example
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'); | |
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