What is generator in JS?
What is generator in JS?
A generator in JavaScript is a special type of function that can pause its execution and later resume from where it left off. This capability is facilitated by the yield
keyword, which is used within the generator function to pause execution and return a value to the caller. When the generator function is resumed, it picks up right after the last yield
statement that was executed.
Generators are defined using the function*
syntax, which distinguishes them from regular functions. Here's a basic example of a generator function:
function* simpleGenerator() {
yield 'First yield';
yield 'Second yield';
return 'Generator done';
}
When this generator function is called, it returns a Generator object but does not execute any of its code immediately. Instead, the code executes in segments, each segment ending at a yield
statement. The next()
method is used on the Generator object to resume execution and move from one yield
to the next. Each call to next()
returns an object with two properties: value
, which is the result of the yield
expression, and done
, which is a boolean indicating whether the generator function has finished executing.
Generators are particularly useful for managing asynchronous operations and complex control flows in a more readable and maintainable way. They allow functions to avoid running to completion immediately, enabling them to handle tasks like iterating over data streams or managing asynchronous interactions without the callback hell or complexity introduced by Promises alone[1][2][3][5][6][12].
Generators also maintain their internal state between executions, maki...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào