Skip to content

Instantly share code, notes, and snippets.

@rkatic
Created May 5, 2017 23:50
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 rkatic/7f521ed23686539e720a3f2fb7e811a3 to your computer and use it in GitHub Desktop.
Save rkatic/7f521ed23686539e720a3f2fb7e811a3 to your computer and use it in GitHub Desktop.
'use strict';
const spawn = generatorFunction => function() {
const gen = generatorFunction.apply(this, arguments);
return new Promise(resolve => {
const handle = (it) => {
if (it.done) {
return it.value;
}
return Array.isArray(it.value)
? Promise.all(it.value).then(cb, eb)
: Promise.resolve(it.value).then(cb, eb);
};
const cb = (result) => handle(gen.next(result));
const eb = (error) => handle(gen.throw(error));
resolve(cb());
});
};
const _isGeneratorFunction = (x) => {
return typeof x === 'function' && x.constructor.name === 'GeneratorFunction';
};
spawn.all = (obj) => {
for (const key in obj) {
if (_isGeneratorFunction(obj[key])) {
obj[key] = spawn(obj[key]);
}
}
return obj;
};
module.exports = spawn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment