Created
May 5, 2017 23:50
-
-
Save rkatic/7f521ed23686539e720a3f2fb7e811a3 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
'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