Async Generators की जानकारी
In this page:
async function* name(): AsyncGenerator<YieldType> {
yield value;
}
for await (const item of name()) {
// use item
}
Basic Async Generator
एक async generator हर yield के बीच asynchronous work await कर सकता है, और इसका return type तीनों value slots के लिए पूरी तरह AsyncGenerator<YieldType, ReturnType, NextType> के रूप में describe किया जा सकता है।
उदाहरण: Basic Async Generator
async function* countAsync(): AsyncGenerator<number, void, unknown> {
yield 1;
yield 2;
}
async function run() {
for await (const n of countAsync()) console.log(n);
}
run();
Async Data Sequences
Async generators naturally fit होते हैं जब भी किसी sequence के हर item को अपना खुद का asynchronous step चाहिए हो — results का एक page एक समय में fetch करना, या अगली value produce करने से पहले एक remote data source पर wait करना।
उदाहरण: Async Data Sequences
async function* fetchPages(): AsyncGenerator<string> {
yield "page 1";
yield "page 2";
}
async function run() {
for await (const page of fetchPages()) console.log(page);
}
run();
Async Generator Return Types
AsyncGenerator के type parameters आपको exactly specify करने देते हैं कि क्या yield होता है, generator ultimately क्या return करता है, और next के through वापस कौन सी type की value pass की जा सकती है — एक regular generator जैसा वही three-part contract, सिर्फ asynchronous।
उदाहरण: Async Generator Return Types
async function* gen(): AsyncGenerator<number, string, unknown> {
yield 1;
return "complete";
}
async function run() {
const it = gen();
console.log(await it.next());
console.log(await it.next());
}
run();
for await...of
for await...of loop specifically async iterators consume करने के लिए बना है — यह automatically हर step के result को await करता है, जो इसे async generators और दूसरे async iterables दोनों के साथ naturally काम करने देता है।
उदाहरण: for await...of
async function* asyncNums(): AsyncGenerator<number> {
yield 10;
yield 20;
}
async function run() {
for await (const n of asyncNums()) {
console.log(n);
}
}
run();
Async Generator Pipelines
Async generators को chain किया जा सकता है एक lazy processing pipeline बनाने के लिए, जहां हर stage अगली value सिर्फ तब pull और process करता है जब इसके बाद वाला stage actually इसे मांगता है।
उदाहरण: Async Generator Pipelines
async function* numbers(): AsyncGenerator<number> {
yield 1;
yield 2;
yield 3;
}
async function* doubled(source: AsyncGenerator<number>): AsyncGenerator<number> {
for await (const n of source) yield n * 2;
}
async function run() {
for await (const n of doubled(numbers())) console.log(n);
}
run();
- एक async generator पर normal
for...ofउपयोग करना, जब इसेfor await...ofचाहिए। async function*लिखना लेकिन इसेGeneratorके बजायAsyncGeneratortyped न करना।- एक
asyncfunction (या top-level module) के बाहरfor awaitउपयोग करना, जो एक error है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: