Last active
August 29, 2015 14:01
-
-
Save jorendorff/b60a186cac7bd56aeeee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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