I was trying to find a clean way to adapt co to be able to be able to yield
promise or non-promise values (e.g. use yield like the `when` method of a
lot of promise libs), so I started hacking out features. By the time I was
through I was pretty surprised to see that it essentially boiled down to
this little block of code (assuming es6 promises):

function run(coroutine) {
return new Promise(function (resolve, reject) {
(function next(value, exception) {
 var result;
try {
result = exception ? coroutine.throw(value) : coroutine.next(value);
 }
catch (error) {
return reject(error);
 }
if (result.done) return resolve(result.value);
Promise.resolve(result.value).then(next, function(error) {
 next(error, true);
});
})();
});
 }

This allows you to yield any promise or non-promise value, and returns a
promise representing the result. You can also use `yield*` to delegate to
other coroutines correctly.

If anyone's interested I wrapped this up and published it to npm as the
`copromise` module. Enjoy!

-- 
Job board: http://jobs.nodejs.org/
New group rules: 
https://gist.github.com/othiym23/9886289#file-moderation-policy-md
Old group rules: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
--- 
You received this message because you are subscribed to the Google Groups 
"nodejs" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/nodejs/CAPm8pjrEXqVuPTBfaGVpThehHe54%3DfT54XQk9jzEjLHukci5RA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to