Drive a Generator Like Async/Await
Write the code, see it run, pass the checks.
The problem
- hard
- Code
- Pro
Before async functions, libraries ran generator functions as if they were async: the generator yields a promise, and the runner resumes it with the resolved value. Write run(generatorFunction, ...args). It calls generatorFunction(...args) to make a generator, then drives it: each value the generator yields is waited for (a value that isn't a promise counts as already resolved) and the generator is resumed with the result. If a yielded promise rejects, throw the error into the generator at that yield, so a try...catch around the yield can handle it. run returns a promise that resolves with the generator's return value, or rejects with any error the generator doesn't catch, including one thrown before its first yield. run itself never throws.
Your code must pass
- Resumes the generator with each resolved value
- Resolves with the generator's return value
- Accepts plain values as well as promises
- Throws rejections back into the generator
- Rejects when the generator throws
- Passes arguments to the generator function