TypeScript async/await : Async Programming In TypeScript
If tutorials available on this website are helpful for you, please whitelist this website in your ad blocker😭 or Donate to help us ❤️ pay for the web hosting to keep the website running.
JavaScript में asynchronous operations को handle करना एक जरूरत ban गया है, और इसको achieve करने के कई तरीके हैं। पिछले कुछ years में, async/await ने Promises और callbacks के complicated syntax को simplify कर दिया है।
TypeScript, जो JavaScript का superset है, async/await के साथ type safety और better development experience provide करता है।
इस topic में हम TypeScript async/await को समझेंगे, इसका syntax, कैसे काम करता है, और कुछ practical examples के साथ इसको explore करेंगे।
●●●
async/await क्या है? (What is async/await?)
async/await JavaScript और TypeScript में asynchronous operations को handle करने का एक modern तरीका है। यह promises के ऊपर build होता है और asynchronous code को लिखना और समझना काफी easy बना देता है।
async keyword function को asynchronous बनाता है, और await का use करके आप किसी promise का result wait कर सकते हैं बिना .then() chains के।
Key Points
async keyword function को asynchronous बनाता है, और यह हमेशा एक Promise return करता है।
await keyword का use करके आप asynchronous operation के complete hone का wait कर सकते हैं बिना chaining के।
try...catch block का use करके error handling को simple बनाया जा सकता है।
●●●
TypeScript async/await Syntax
अब समझते हैं कि async/await का basic syntax क्या होता है और यह कैसे काम करता है।
async function myAsyncFunction() {
try {
const result = await someAsyncOperation();
console.log(result);
} catch (error) {
console.error('Error:', error);
}
}Explanation
asynckeyword function के आगे लगता है, जो promise को implicitly return करता है।awaitkeyword asynchronous operation का result wait करने के लिए use होता है। await के बिना promise return होता, लेकिन इसके साथ आपको promise का resolved value मिलता है।try...catchblock का use करके error handling करना काफी easy हो जाता है।
●●●
TypeScript async-await Example
अब एक real-world example देखते हैं जिसमे हम एक asynchronous operation का use करते हैं तो API से data fetch कर सकें, और उस data को handle करते हैं async/await के साथ।
interface User {
id: number;
name: string;
email: string;
}
// Simulating an API request
function fetchUser(userId: number): Promise<User> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId === 1) {
resolve({
id: 1,
name: "John Doe",
email: "john.doe@example.com",
});
} else {
reject("User not found");
}
}, 2000);
});
}
// Using async/await to handle the asynchronous function
async function getUserData(userId: number): Promise<void> {
try {
const user = await fetchUser(userId);
console.log(`User fetched: ${user.name}, Email: ${user.email}`);
} catch (error) {
console.error("Error:", error);
}
}
getUserData(1); // Output after 2 seconds: User fetched: John Doe, Email: john.doe@example.com
Explanation
fetchUser()function एक promise return करता है जो 2 seconds बाद user का data resolve करता है अगरuserId 1है, और reject करता है अगर user नहीं मिलता।getUserData function में
async/awaitका use किया गया है तो user data को fetch करने के लिए। अगर promise resolve होता है, तो result को console पर print किया जाता है। अगर error होती है, तोcatch()block उस error को handle करता है।
●●●
Handling Multiple await Calls Sequentially
TypeScript में आप multiple asynchronous operations को sequentially perform कर सकते हैं by using await keyword multiple times . जब एक await call complete होता है, तब दूसरा await call execute होता है।
async function fetchDataSequentially() {
try {
const user = await fetchUser(1);
console.log("User:", user);
const user2 = await fetchUser(2);
console.log("Second User:", user2);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchDataSequentially();
// Output:
// User: { id: 1, name: 'John Doe', email: 'john.doe@example.com' }
// Error: User not foundExplanation
fetchUser(1)को पहले resolve hone दिया गया, और फिरfetchUser(2)को wait किया गया।अगर पहला await resolve होता है, तो दूसरा await execute होता है।
अगर कोई promise reject होता है, तो
catchblock में उस error को handle किया जाता है।
●●●
TypeScript async-await Using Promise.all()
अगर आपको multiple asynchronous operations को parallel में execute करना हो, तो आप Promise.all() का use कर सकते हैं।
इससे सारे asynchronous operations एक साथ चलेंगे और जब सब complete हो जायेंगे तब result मिलेगा।
async function fetchMultipleUsers() {
try {
const [user1, user2] = await Promise.all([fetchUser(1), fetchUser(2)]);
console.log("User 1:", user1);
console.log("User 2:", user2);
} catch (error) {
console.error("Error fetching users:", error);
}
}
fetchMultipleUsers();Output
// User 1: { id: 1, name: 'John Doe', email: 'john.doe@example.com' }
// Error fetching users: User not found●●●
Returning Values from async Functions
आप async function के through values को return कर सकते हैं। async function हमेशा एक promise return करता है, चाहे आप explicit return करें या नहीं।
async function getUserName(userId: number): Promise<string> {
const user = await fetchUser(userId);
return user.name;
}
getUserName(1)
.then((name) => {
console.log(`User name is ${name}`);
})
.catch((error) => {
console.error("Error fetching user name:", error);
});
// Output: User name is John Doe●●●
Common Mistakes While Using async/await
1. Forgetting await
अगर आप await का use भूल जाते हैं, तो Promise का object return होगा instead of थे resolved value.
async function fetchData() {
const user = fetchUser(1); // Missing 'await'
console.log(user); // Output: Promise {<pending>}
}2. Not Handling Rejections
अगर आप try...catch block का use नहीं करते, तो unhandled promise rejection error आ सकती है।
async function fetchData() {
const user = await fetchUser(2); // This will throw an error
console.log(user); // Error: UnhandledPromiseRejectionWarning
}Conclusion
TypeScript में async/await asynchronous programming को simple और readable बनाता है. यह promises के ऊपर build होता है, लेकिन .then() chaining से बचाता है और error handling को easy बनाता है।
इसका use कर के आप complex asynchronous code को भी readable और maintainable बना सकते हैं।