Skip to content

Instantly share code, notes, and snippets.

@stormoz
Last active September 1, 2016 21:48
Show Gist options
  • Save stormoz/67766ff7d10042e52b2ad0a56c0fb298 to your computer and use it in GitHub Desktop.
Save stormoz/67766ff7d10042e52b2ad0a56c0fb298 to your computer and use it in GitHub Desktop.
function callAsync(fn) {
// get iterator
var iterator = fn();
// used as a callback to currently yielded functions
function next() {
// get next function
var current = iterator.next();
// recursion exit condition
if (current.done) { return; }
// call async function and pass next() as aa callback so it will ask the iterator to yield next when callback is called
var promise = current.value;
promise.then(next);
}
// initialise recursion
next();
}
// delay function as a simple example of something that returns promise
function delay(timeout) {
return new Promise((resolve, reject) => setTimeout(resolve, timeout));
}
callAsync(function* () {
yield delay(1000);
console.log('waited for 1 sec');
yield delay(2000);
console.log('waited for 2 sec');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment