How can generators be used to implement coroutines or cooperative multitasking in JavaScript?
Difficulty: 6/10
generators, coroutines, cooperative multitasking
Generators can yield control back to a scheduler, allowing multiple tasks to run interleaved (cooperative multitasking) without threads.
Coroutine scheduler
Scenario Questions
0-2 years experience
1Write a generator that yields the numbers 1 through 5 and show how you would manually call next() to pause and resume it as a tiny cooperative task.
2If you call next() on a generator that has already completed, what does JavaScript return, and how would you guard against that in a simple scheduler?
3How could you use a generator to create a very small async/await polyfill for a function that returns a Promise?
2-5 years experience
1We have a UI component that fetches data, renders it, then waits for a button click before continuing. How would you orchestrate that flow with a generator instead of callbacks or async/await?
2During a code review you notice a generator‑based coroutine that sometimes hangs after an exception is thrown. What could cause the hang and how would you fix it?
3What are the trade‑offs of using a generator‑driven task runner versus a promise‑based one in a Node.js microservice that processes a stream of events?
5-8 years experience
1Design a cooperative multitasking scheduler for thousands of lightweight tasks in a browser game using generators. Which data structures and scheduling policy would you pick to keep the main thread responsive?
2Our server uses a generator‑driven pipeline to handle incoming requests, and under load we see memory usage climb. Identify possible sources of memory leakage in generator usage and propose mitigations.
3Compare the performance and debuggability of a generator‑based coroutine system versus async/await in a large codebase. When would you recommend each approach?
8+ years experience
1We need to migrate a legacy codebase that relies on custom generator coroutines to a modern async/await architecture across several teams. How would you plan and execute that migration to minimize risk?
2At the organization level, we are debating whether to standardize on generator‑based cooperative multitasking for all client‑side state machines. What architectural, tooling, and developer‑experience factors would influence that decision?
3How would you design a cross‑team library that abstracts generator coroutines, providing a uniform API while allowing teams to plug in different scheduling strategies such as frame‑based, time‑slice, or priority queues?
Follow-up Questions
What happens if a generator throws an error and the scheduler doesn't catch it?
How would you expose this coroutine pattern to other developers on the team?
Can you compare this approach to using async/await in terms of stack traces?
Sharethis question
Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.