Skip to content

Instantly share code, notes, and snippets.

@ahamedali95
Last active May 11, 2020 00:44
Show Gist options
  • Save ahamedali95/dd5464c40a9712c66e61c42352407b16 to your computer and use it in GitHub Desktop.
Save ahamedali95/dd5464c40a9712c66e61c42352407b16 to your computer and use it in GitHub Desktop.
const AsyncModule = generator => {
return () => {
const iterator = generator();
const resolve = next => {
if (next.done) {
return Promise.resolve(next.value);
}
return Promise.resolve(next.value).then(response => {
//recursively call resolve() until done is `true`
return resolve(iterator.next(response));
});
};
return resolve(iterator.next());
};
};
const asyncGenerator = function*() {
const response = yield fetch('https://pokeapi.co/api/v2/pokemon');
const json = yield response.json();
return json;
};
const getData = AsyncModule(asyncGenerator);
console.log(getData().then(d => console.log(d))); =>//prints api data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment