Are JavaScript generators functionally equivalent to coroutines in other languages?

ECMAScript 6 implements a feature called "generators".

"Generators" seem functionally equivalent to "coroutines" from other programming languages. JavaScript even uses the same keywords as yield in these generators.

If they work the same way, or at least have the same concept, why are they called โ€œgeneratorsโ€ in JavaScript and โ€œcoroutinesโ€ in others?

The only possible reason why I can think about why this is so is because the generators are functionally different, so they gave it a different name, but after looking at some code I'm not sure.

Here are two functions that coroutines / generators use in Python and JavaScript, just so you can compare.

(From Tasks and coroutines in Python documentation)

 import asyncio import datetime @asyncio.coroutine def display_date(loop): end_time = loop.time() + 5.0 while True: print(datetime.datetime.now()) if (loop.time() + 1.0) >= end_time: break yield from asyncio.sleep(1) loop = asyncio.get_event_loop() # Blocking call which returns when the display_date() coroutine is done loop.run_until_complete(display_date(loop)) loop.close() 

(From Iterators and Generators in the MDN documentation)

 function* idMaker(){ var index = 0; while(true) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 

I would like to add that my programming knowledge is not very different from JavaScript.

I have been stuck with JavaScript for 4+ years. Perhaps this is a gap in my knowledge, so I ask here.

+4
source share

All Articles