My attempt on asyncToGenerator()
YCM Jason

YCM Jason @ycmjason

About: I cook delicious TypeScript / JavaScript nuggets. 🍳

Location:
London, UK
Joined:
Sep 30, 2017

My attempt on asyncToGenerator()

Publish Date: May 3 '18
7 2

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

Comments 2 total

  • Manuel Romero
    Manuel RomeroMay 5, 2018

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

    • YCM Jason
      YCM JasonMay 6, 2018

      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.

Add comment