Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active August 29, 2015 14:01
Show Gist options
  • Save jorendorff/b60a186cac7bd56aeeee to your computer and use it in GitHub Desktop.
Save jorendorff/b60a186cac7bd56aeeee to your computer and use it in GitHub Desktop.
// Here is an example of a plain old function that returns a promise.
// Nothing magic about that.
function sleep(sec) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(undefined);
}, sec * 1000);
});
}
// Now, as requested, a generator that we're converting into a
// function-that-returns-a-promise using the decorator co().
var g = co(function* () {
yield sleep(0.3);
console.log("at 0.3sec");
yield sleep(0.2);
console.log("at 0.5sec");
yield sleep(0.4);
console.log("done");
return "squeamish ossifrage";
});
// When we call g(), it returns a promise for
// the generator's eventual return value.
g().then(function (result) {
console.log("promise resolved! the magic words are:", result);
});
// And here is the definition of co().
function co(g) {
return function(...args) {
return new Promise(function (resolve, reject) {
var gen = g(...args);
function next(value) {
var result;
try {
result = gen.next(value);
} catch (exc) {
reject(exc);
return;
}
if (result.done) {
resolve(result.value);
return;
}
result.value.then(next, reject);
}
setTimeout(() => next(undefined), 0);
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment