Types के साथ Async/Await
In this page:
async function name(): Promise<returnType> {
const result = await promiseExpression;
return result;
}
Typed Async Functions
एक async function का return type compiler द्वारा अपने आप Promise<T> में wrap हो जाता है, तो async (): Promise<number> के रूप में declare की गई function और async (): number के रूप में declare की गई function compile होने के बाद एक जैसा behave करती हैं।
उदाहरण: Typed Async Functions
async function getCount(): Promise<number> {
return 5;
}
getCount().then((n) => console.log(n));
Fetch Responses को Await करना
एक typed fetch response को await करना — const data: User = await response.json() — promise की value को annotated type के साथ resolve करता है, हालांकि याद रखें .json() खुद shape validate नहीं करता, सिर्फ वह type assign करता है जो आप assert करते हैं।
उदाहरण: Awaiting Fetch Responses
interface User { name: string; }
async function getUser(): Promise<User> {
const response = await fetch("data.php");
const data: User = await response.json();
return data;
}
getUser().then((u) => console.log(u.name));
Sequential Async Operations
Sequential async operations, हर एक को एक के बाद एक await करते हुए, produce होते ही हर intermediate result को individually type करते हैं, हर step के output को पूरी type information के साथ अगले step के consume करने के लिए available बनाते हुए।
उदाहरण: Sequential Async Operations
async function step1(): Promise<number> { return 1; }
async function step2(n: number): Promise<number> { return n + 1; }
async function run() {
const a = await step1();
const b = await step2(a);
console.log(b);
}
run();
Parallel Async Operations
Parallel async operations Promise.all के through चलती हैं, जो इसके result को हर input promise के resolved type से order में match करने वाला एक tuple type करता है, आपको पूरी type safety के साथ कई concurrent results destructure करने देते हुए।
उदाहरण: Parallel Async Operations
async function getA(): Promise<number> { return 1; }
async function getB(): Promise<string> { return "b"; }
async function run() {
const [a, b] = await Promise.all([getA(), getB()]);
console.log(a, b);
}
run();
Async Error Handling
try/catch के साथ Async error handling caught value को synchronous code की तरह ही unknown type करती है, तो .message पढ़ने से पहले इसे instanceof Error से narrow करना एक async function के अंदर भी वैसे ही apply होता है।
उदाहरण: Async Error Handling
async function risky(): Promise<number> {
throw new Error("failed");
}
async function run() {
try {
await risky();
} catch (err: unknown) {
if (err instanceof Error) console.log(err.message);
}
}
run();
awaitभूल जाना, इसलिए variableUserके बजाय एकPromise<User>रखता है।async function getCount(): numberलिखना, जब एक async function कोPromise<number>के रूप में type किया जाना चाहिए।- Independent calls को
Promise.allउपयोग करने के बजाय एक के बाद एक await करना, उन्हें धीमा बनाते हुए।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: