How does yield pause and resume execution, and what does it return to the caller?
Short answer
When a generator hits yield, execution pauses immediately and control returns to the caller with an object { value, done: false } — the generator's internal state (including local variables) is preserved until next() is called again, which resumes execution right after that…
Advertisement
AModel answer
When a generator hits yield, execution pauses immediately and control returns to the caller with an object { value, done: false } — the generator's internal state (including local variables) is preserved until next() is called again, which resumes execution right after that yield.
function* logger() {
console.log('before');
const received = yield 'paused-value';
console.log('resumed with:', received);
}
const it = logger();
it.next(); // logs 'before', returns { value: 'paused-value', done: false }
it.next('hello'); // logs 'resumed with: hello'Real-world example
Building a step-by-step wizard flow where each step waits for external input before continuing.
Likely follow-ups
- How do you pass a value INTO a generator via next(), as opposed to getting one out via yield?
Related topics