Created
February 3, 2016 02:26
-
-
Save clark800/329d5b89e36c010d82bd to your computer and use it in GitHub Desktop.
simplified co
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'; | |
function isGenerator(obj) { | |
return typeof obj.next === 'function' && typeof obj.throw === 'function'; | |
} | |
// co returns a promise that resolves to the return value of the generator arg | |
function co(generator) { | |
return new Promise(resolve => { | |
function next(result) { | |
const step = generator.next(result); | |
const yieldedValue = step.value; | |
if (step.done) { | |
return yieldedValue; | |
} | |
if (yieldedValue instanceof Promise) { | |
return yieldedValue.then(next); | |
} | |
if (isGenerator(yieldedValue)) { | |
return co(yieldedValue).then(next); | |
} | |
} | |
resolve(next()); | |
}); | |
} | |
function square(x) { | |
return new Promise(resolve => { | |
setTimeout(() => resolve(x * x), 500); | |
}); | |
} | |
function sum(x, y) { | |
return new Promise(resolve => { | |
setTimeout(() => resolve(x + y), 500); | |
}); | |
} | |
function * sumSquares(x, y) { | |
return yield sum(yield square(x), yield square(y)); | |
} | |
function * main() { | |
console.log('2^2 + 3^2 = ' + (yield sumSquares(2, 3))); | |
console.log('3^3 + 4^2 = ' + (yield sumSquares(3, 4))); | |
} | |
co(main()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment