DEV Community

YCM Jason
YCM Jason

Posted on

My attempt on asyncToGenerator()

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');
  };
}
Enter fullscreen mode Exit fullscreen mode

To use:

asyncToGenerator(function* () {
  const res = yield axios.get('https://www.ycmjason.com');
  console.log(res);
})();
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
mrm8488 profile image
Manuel Romero

I created a module to do something similar: github.com/mrm8488/asyncflow

Collapse
 
ycmjason profile image
YCM Jason

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.