Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Last active March 2, 2017 15:35
Show Gist options
  • Save zeusdeux/c79c45e53489cc5cb09bf6ab8bb2258f to your computer and use it in GitHub Desktop.
Save zeusdeux/c79c45e53489cc5cb09bf6ab8bb2258f to your computer and use it in GitHub Desktop.
Simple co implementation that works with only promises. It Let's you write sync code using generators and promises.
function co(genInstance) {
const success = v => step(genInstance, {value: v, failed: false})
const failure = err => step(genInstance, {error: err, failed: true})
if ('function' === typeof genInstance) genInstance = genInstance()
// kick start generator
const retVal = genInstance.next()
if (retVal.done) return retVal.value
else return retVal.value.then(success, failure)
function step(g, o) {
let retVal
if (!o.failed) retVal = g.next(o.value)
else retVal = g.throw(o.error)
if (retVal.done) return retVal.value
else retVal.value.then(success, failure)
}
}
function *a() {
var v = yield new Promise((r) => setTimeout(() => {
console.log('resolving promise 1 with "dude"')
r('dude')
}, 2000))
try {
var a = yield new Promise(() => {
var msg = `last value was ${v}`
console.log('rejecting promise with error. Msg is "', msg, '"')
throw new Error(msg)
})
} catch(e) {
console.error(e)
console.log(`a is ${a}. It should be undefined`)
var p = yield Promise.resolve('man')
}
console.log('p is', p)
try {
var r = yield Promise.reject('i am a rejected promise')
console.log('this will never be reached')
} catch (e) {
console.error(e)
}
var m = yield new Promise(r => setTimeout(() => r(8888), 4000))
console.log(`m is ${m}`)
}
function *a() {}
function *b() {
return yield Promise.resolve(10)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment