Skip to content

Instantly share code, notes, and snippets.

@carlosrberto
Created July 11, 2017 14:00
Show Gist options
  • Save carlosrberto/9e315290bcd65ca53c3d8105bf0f0f1c to your computer and use it in GitHub Desktop.
Save carlosrberto/9e315290bcd65ca53c3d8105bf0f0f1c to your computer and use it in GitHub Desktop.
Async code execution with generators
const isPromise = fn => fn && fn.then;
const getUser = () => new Promise((resolve, reject) => {
setTimeout(()=> {
resolve({name: 'John Lavoier'});
}, 2000);
});
const getProfile = () => new Promise((resolve, reject) => {
setTimeout(()=> {
resolve({job: 'JavaScript Programmer', city: 'Ribeirão Preto'});
}, 4000);
});
const runAsyncCode = (fn) => {
const gen = fn();
let nextValue;
const next = (nextParam) => {
nextValue = nextParam ? gen.next(nextParam) : gen.next();
if(!nextValue.done) {
if(isPromise(nextValue.value)) {
nextValue.value.then(v => next(v));
} else {
next(nextValue.value);
}
}
}
next();
}
function* asyncCalls() {
const randomValue = yield "just a random value";
console.log('print random', randomValue);
const user = yield getUser();
console.log(`the user name is ${user.name}`);
const profile = yield getProfile();
console.log(`user job: ${profile.job}, user city: ${profile.city}`);
}
runAsyncCode(asyncCalls);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment