Send values and errors into generators
Quick answer
A suspended generator can receive a value through next(value), an exception through throw(error), or a completion request through return(value).
How it works
The argument of the first next is ignored because execution has not yet reached a suspended yield. Later next arguments become the result of the previous yield expression. throw injects an exception at that point, allowing a surrounding try/catch to recover. return requests completion, executing relevant finally blocks; a yield in finally can delay completion. Calls after completed state cannot restart the generator.
function* g(){const x=yield "ready";yield x*2;} const it=g();console.log(it.next(99).value,it.next(4).value);Expected output in Node.js:
ready 8The first argument is ignored; the second resumes the yield.
function* g(){try{yield "wait";}catch(e){yield e.message;}} const it=g();it.next();console.log(it.throw(new Error("stop")).value,it.next().done);Expected output in Node.js:
stop trueThe catch handles the injected error and yields its message.
Common mistakes
Do not use generators as ordinary functions expecting the first next argument to become a parameter. Use explicit generator parameters for initialization.
Practice
Trace a three-step conversation with a generator, then inject a controlled Error after the first yield.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Send values and errors into generators — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which next argument is ignored for a newly created generator?
Where is an error injected by generator.throw?
What can delay completion after generator.return?
What is the exact console output in Send values and errors into generators example 1?
function* g(){const x=yield "ready";yield x*2;} const it=g();console.log(it.next(99).value,it.next(4).value);What is the exact console output in Send values and errors into generators example 2?
function* g(){try{yield "wait";}catch(e){yield e.message;}} const it=g();it.next();console.log(it.throw(new Error("stop")).value,it.next().done);