Not gonna explain so much, just sharing my recent attempt on implementing asyncToGenerator()
. Please do tell me what you think. 😀
function asyncToGenerator(fn) {
const ensurePromise = v => Promise.resolve(v);
const stepContext = (context, nextOrThrow, prev) => {
const { value, done } = context[nextOrThrow](prev);
if (done) return ensurePromise(value);
return ensurePromise(value)
.then(v => stepContext(context, 'next', v))
.catch(err => stepContext(context, 'throw', err));
};
return function(...args) {
const context = fn.apply(this, args);
return stepContext(context, 'next');
};
}
To use:
asyncToGenerator(function* () {
const res = yield axios.get('https://www.ycmjason.com');
console.log(res);
})();
Top comments (2)
I created a module to do something similar: github.com/mrm8488/asyncflow
Nice work!
It's just a proof of concept I guess. We all use async/await nowadays! But it's really fun to try to write this from scratch.