ES6 Generator在V8引擎中的暂停机制及数据存储原理
Great question—Generators are one of those ES6 features that look straightforward on the surface but hide some really clever engineering in V8. Let’s break down your questions one by one:
一、Generator内部待返回数据的存储位置
When you create a generator instance (like const gen_ = gen() in your example), V8 creates an internal object called a GeneratorObject to manage the generator’s entire lifecycle. This object stores all the state needed to resume execution later, including:
- The values you’ve specified with
yield(like 1, 2, 3 in your code) - The exact position in the code where execution was paused
- The current execution context (including variables, scope chain, and other runtime state)
In your example, after calling gen_.next() and getting back {value: 1, done: false}, the value 1 is stored directly in this GeneratorObject—it’s waiting there until the next next() call triggers the generator to move to the next yield.
二、V8如何实现“等待消费者请求再恢复执行”
V8 uses coroutines (lightweight user-space threads) to power Generators. Here’s a step-by-step breakdown of how it works with your code:
- When you call
gen()(the generator function), V8 doesn’t execute the function body immediately. Instead, it creates a new coroutine and wraps it in theGeneratorObjectwe mentioned earlier, leaving the coroutine in a suspended state. - The first time you call
gen_.next(), V8 switches execution to this coroutine. It runs the generator function body until it hits the firstyield 1statement. - At this point, V8 suspends the coroutine: it saves the current execution context to the
GeneratorObject, then returns the yielded value (1) to the caller along withdone: falseto signal there’s more data coming. - When you call
gen_.next()again, V8 reactivates the suspended coroutine. It restores the saved execution context from theGeneratorObject, then resumes execution exactly where it left off—right after the firstyield—and runs until it hitsyield 2. The same suspend-and-return process repeats. - This cycle continues until the generator function reaches its end (or a
returnstatement), at which pointnext()returns{value: undefined, done: true}.
To put it simply: Generators let you pause and resume a function’s execution by leveraging coroutines, with all the necessary state stored in a dedicated internal object managed by V8.
内容的提问来源于stack exchange,提问作者nujabes

