Promise के Types
In this page:
const promise: Promise<Type> = new Promise((resolve, reject) => {
resolve(value);
});
Basic Promise Types
एक basic Promise<T> type describe करता है कि promise आखिरकार किस value के साथ resolve होगी, तो Promise<string> return करने वाली एक function await होने पर एक string देने का promise करती है, अभी नहीं।
उदाहरण: Basic Promise Types
function getGreeting(): Promise<string> {
return Promise.resolve("hello");
}
getGreeting().then((s) => console.log(s));
Object Types वाले Promises
एक object type के साथ resolve होने वाला promise — Promise<User> — आपको इसे await करने के बाद resolved object की properties पूरी autocomplete के साथ access करने देता है, exactly जैसे आपको object synchronously मिला हो।
उदाहरण: Promises with Object Types
interface User { name: string; }
function getUser(): Promise<User> {
return Promise.resolve({ name: "Ravi" });
}
getUser().then((u) => console.log(u.name));
Promise Arrays
Promises का एक array, Promise<T>[] के रूप में type किया गया, कई concurrent operations शुरू करने के बाद उन्हें together await करने का एक आम shape है, Promise<T[]> से अलग जो एक array से resolve होने वाला एक single promise है।
उदाहरण: Promise Arrays
const tasks: Promise<number>[] = [Promise.resolve(1), Promise.resolve(2)];
console.log(tasks.length);
Promise.all और Promise Types
Promise.all promises के एक array को उनके results के एक array से resolve होने वाले एक promise में convert करता है, और इसका type signature हर result का type corresponding input promise से अपने आप infer करता है।
उदाहरण: Promise.all and Promise Types
const tasks: [Promise<number>, Promise<string>] = [Promise.resolve(1), Promise.resolve("a")];
Promise.all(tasks).then(([n, s]) => console.log(n, s));
Promise Rejection Types
एक rejected promise का type TypeScript में unknown है, जो यह mirror करता है कि caught exceptions कैसे type होते हैं, क्योंकि JavaScript literally किसी भी value के साथ एक promise reject करने देता है, ज़रूरी नहीं कि एक Error instance हो।
उदाहरण: Promise Rejection Types
Promise.reject("custom string reason").catch((reason: unknown) => {
console.log("Rejected with:", reason);
});
- एक function जो promise return करती है उसके लिए return type
stringलिखना बजायPromise<string>के। - Rejection handle किए बिना
.thenresult उपयोग करना, इसलिए errors unhandled रह जाती हैं। - Promises का एक array
Promise.allको pass करना और बिनाawaitएक plain array वापस मिलने की उम्मीद करना।
- Fetch API और Axios types के साथ उपयोग किए जा सकते हैं ताकि requests और responses जांचे जाएं।
- API responses के लिए types define करना यह document करता है कि आपका code क्या data expect करता है।
- Typed error handling,
async/await, औरPromisetypes asynchronous code को predictable रखते हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: