4

I am interested in using a generator + promise pattern where the promise will iterate through the generator, resolve each yielded value, and pass it back into the generator. Once it's done, the promise resolves with the final return (if any).

I found an elegant implementation provided by promisejs.org at the bottom of this page, but after studying it for a bit it seems to me like this would be a memory leak for long-running or infinite generators. I'm hoping to be corrected.

I've simplified it by removing error checking and using arrow functions for readability:

function async(generator){
  function handle(result) {
    return result.done
      ? Promise.resolve(result.value)
      : Promise.resolve(result.value)
               .then(res => handle(generator.next(res)));
  }

  return handle(generator.next());
}

It seems to me like the each iteration of handle returns a new promise that won't resolve until the generator completes, and then they all cascade up. Is that the case, and if so does that mean this would collapse with enough iterations?

Mark
  • 999
  • 9
  • 19
  • 1
    Wow, good and thoughtful question - and an exact duplicate :-) – Bergi Nov 27 '17 at 18:36
  • "*I am interested in using a generator + promise pattern*" - don't. Go for `async`/`await` syntax right away, it achieves exactly the same. – Bergi Nov 27 '17 at 18:38
  • Whoops. My search was overly specific to generators and not the core issue. Thanks for the link. Edit: Just saw your comment... thanks for the pointer, I'll look into that. – Mark Nov 27 '17 at 18:45

0 Answers0