My attempt on asyncToGenerator()

YCM Jason - May 3 '18 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .