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?