Skip to content

Instantly share code, notes, and snippets.

@craigdallimore
Created September 25, 2016 18:01
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 craigdallimore/ff629bbf9d4d06eeebc2501204864fa5 to your computer and use it in GitHub Desktop.
Save craigdallimore/ff629bbf9d4d06eeebc2501204864fa5 to your computer and use it in GitHub Desktop.
// A function that takes a number and returns a Promise for nothing but
// some logging side effects.
const vow = num => new Promise(resolve => {
console.log(`start ${num}`);
setTimeout(() => {
console.log(`done ${num}`);
resolve();
}, Math.random() * 500);
});
// These promises will all start at about the same time
// and finish in an unpredictable way.
vow(1);
vow(2);
vow(3);
// These promises will each start when the previous one is done.
function* seq() {
yield vow(4);
yield vow(5);
yield vow(6);
}
// A cheap and hacky coroutine.
const run = generator => {
const iterate = result => result.done
? Promise.resolve(result.value)
: Promise.resolve(result.value)
.then(p => iterate(generator.next(p)),
e => iterate(generator.throw(e)));
try {
return iterate(generator.next());
} catch (e) {
return Promise.reject(e);
}
};
setTimeout(() =>
run(seq());
}, 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment