DEV Community

Discussion on: What’s your favorite JS interview question?

Collapse
 
kevinoca profile image
Kevin Oca

Beside your question, Can i ask where it becomes usefull to use generators? i know about them but haven't used yet in production code.

-Performance optimizations maybe?

Collapse
 
misterwhat profile image
Jonas Winzen

They are useful wherever you want to suspend and handle control (and optionally a value) back to the caller. When the caller is done doing its stuff, he can decide to give you back control (also optionally with a value). Your function continues where it has stopped before.

A prominent use case are CSP (communicating sequencial processes) style concurrency models, where multiple processes read and write to and from a shared channel. Processes can block and wait until some specified message type is observed on the channel. On the other hand, processes can write to the channel, without caring if there is another process that would make use of the message (you could write error log messages to the channel but only display them in dev mode and otherwise send them to a remote endpoint for further processing them in e.g. Kibana).

The great advantage of this model is the loose coupling that allows you to simply swap out or replace parts of your application depending on your needs.