English
JavaScript generators are a special type of function that can pause their execution and later resume it. They are defined using a function with an asterisk (*) symbol, like this:
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
In this example, myGenerator is a generator function that yields (produces) values one by one using the yield keyword. When you call this generator function, it doesn't run immediately. Instead, it returns an iterator object.
To use the generator and retrieve values, you can create an iterator and use the next() method:
const iterator = myGenerator();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Each time you call iterator.next(), the generator function runs until it encounters a yield statement, at which point it yields the value and pauses. You can then resume the execution by calling next() again.
Hindi
JavaScript generators ek khaas prakar ke function hain jo apne execut ko rok sakte hain aur baad mein use dubara chala sakte hain. Inhe ek function mein anokha (*) chihn laga kar define kiya jata hai, jaise ki yeh:
function* meraGenerator() {
yield 1;
yield 2;
yield 3;
}
Is udaharan mein, meraGenerator ek generator function hai jo yield shabd ka upayog karke ek ek karke mulyon ko utpann (produce) karta hai. Jab aap is generator function ko bulata hai, toh yeh turant nahin chalta. Balki, yeh ek iterator object lautata hai.
Generator ka upayog karne aur mulyon ko prapt karne ke liye, aap ek iterator bana sakte hain aur next() method ka upayog kar sakte hain:
const iterator = meraGenerator();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Har bar jab aap iterator.next() ko bulate hain, toh generator function tab tak chalta hai jab tak vah ek yield statement ko nahin milta, us samay vah muly ko utpann karta hai aur rok jata hai. Phir se chalaane ke liye aap next() ko fir se bulate hain.
Top comments (0)