Last active
May 29, 2021 00:16
-
-
Save patrickroberts/b909df473ca25dbb66e5e5adb4a78d6f to your computer and use it in GitHub Desktop.
Coroutine microimplementation
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
export default function co(gen) { | |
return function (...args) { | |
const iter = Function.prototype.apply.call(gen, this, args); | |
const resume = (value) => { | |
try { | |
const result = iter.next(value); | |
const promise = Promise.resolve(result.value); | |
return result.done ? promise : promise.then(resume); | |
} catch (error) { | |
return Promise.reject(error); | |
} | |
}; | |
return resume(undefined); | |
}; | |
} |
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
import co from './co'; | |
function sleep(ms, value) { | |
return new Promise((resolve) => { | |
setTimeout(() => resolve(value), ms); | |
}); | |
} | |
const asyncAdd = co(function* genAdd(a, b) { | |
console.log('Sleeping'); | |
console.log(`Slept for ${yield sleep(3000, '3 seconds')}`); | |
return a + b; | |
}); | |
asyncAdd(3, 4).then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment