जेनरेटर फंक्शन (function*) विशेष फंक्शन हैं जिन्हें रोका और फिर से शुरू किया जा सकता है, जिससे वे अपनी स्थिति बनाए रखते हैं। वे yield कीवर्ड का उपयोग करके मान उत्पन्न करते हैं और Iterator प्रोटोकॉल का पालन करते हैं।
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.sample { font-size: 18px; font-weight: 500; line-height: 2; }
button { padding: 10px 20px; background: #e83e8c; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style> </head> <body>
<h1>JavaScript Generator फंक्शन</h1>
<div class="sample"></div>
<button class="Btn">जेनरेटर से अगला मान प्राप्त करें</button>
<h3>बटन पर क्लिक करके जेनरेटर फंक्शन को कॉल करें और परिणाम उत्पन्न करें</h3>
<script>
const sampleEle = document.querySelector(".sample");
// जेनरेटर फंक्शन परिभाषा
function* generate(num) {
yield 2 * num;
yield 3 * num;
yield 4 * num;
yield 5 * num;
}
// जेनरेटर ऑब्जेक्ट बनाएं (फंक्शन अभी नहीं चलता)
const Gen = generate(8);
document.querySelector(".Btn").addEventListener("click", () => {
const next = Gen.next();
if (!next.done) {
sampleEle.innerHTML += "उत्पन्न मान: " + next.value + "<br>";
} else {
sampleEle.innerHTML += "जेनरेटर समाप्त<br>";
}
});
</script> </body> </html>
आउटपुट (प्रत्येक क्लिक पर)
- उत्पन्न मान: 16
- उत्पन्न मान: 24
- उत्पन्न मान: 32
- उत्पन्न मान: 40
- जेनरेटर समाप्त
जेनरेटर ऑब्जेक्ट मेथड्स
| मेथड | विवरण |
|---|---|
next(value) | अगला yield तक निष्पादित करता है, {value, done} लौटाता है |
return(value) | जेनरेटर समाप्त करता है, {value, done: true} लौटाता है |
throw(error) | जेनरेटर के अंदर त्रुटि फेंकता है |
उन्नत पैटर्न
1. अनंत अनुक्रम
function* idGenerator() {
let id = 0;
while (true) yield id++;
}
const gen = idGenerator();
gen.next().value; // 0
gen.next().value; // 1
2. डेलीगेशन (yield*)
function* inner() { yield 1; yield 2; }
function* outer() { yield 0; yield* inner(); yield 3; }
[...outer()]; // [0, 1, 2, 3]
3. एसिंक्रोनस फ्लो कंट्रोल
async function run(generator) {
const iterator = generator();
const iterate = (val) => {
const { value, done } = iterator.next(val);
if (done) return value;
return Promise.resolve(value).then(iterate);
};
return iterate();
}
run(function* () {
const user = yield fetchUser(1);
const posts = yield fetchPosts(user.id);
return posts;
});
4. पुनरावृत्त करने योग्य ऑब्जेक्ट बनाना
const iterable = {
*[Symbol.iterator]() {
yield 1; yield 2; yield 3;
}
};
[...iterable]; // [1, 2, 3]