English
Promises:
Promises are a way to handle asynchronous operations in a more organized and readable manner. They represent a value that might be available now, or in the future, or never.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Fetched data from server";
// Simulating success
resolve(data);
// Simulating error
// reject("Error fetching data");
}, 2000);
});
}
fetchData()
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
Async/Await:
Async/Await is a more recent feature in JavaScript that simplifies asynchronous code even further. It allows you to write asynchronous code that looks similar to synchronous code, making it easier to understand and maintain.
async function fetchDataAsync() {
try {
const response = await fetchData();
console.log(response);
} catch (error) {
console.error(error);
}
}
fetchDataAsync();
Hindi
Promises:
Promises ek tareeka hai asynchronus operations ko ek vyavasthit aur padhne mein sahaj tarike se handle karne ka. Ye ek aisa mauka hai jo abhi maujood ho sakta hai, ya bhavishya mein ho sakta hai, ya kabhi na ho.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Server se data liya gaya";
// Utpanna huaa safalata
resolve(data);
// Utpanna huaa karan
// reject("Data liye jaane mein error");
}, 2000);
});
}
fetchData()
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
Async/Await:
Async/Await ek nedee haaal mein JavaScript mein aayi feature hai jo asynchronus code ko aur bhi saral bana deti hai. Isse aap aisa asynchronus code likh sakte hain jo sankramit code ki tarah lagta hai, jisse samajhna aur maintain karna aasan ho jata hai.
async function fetchDataAsync() {
try {
const response = await fetchData();
console.log(response);
} catch (error) {
console.error(error);
}
}
fetchDataAsync();
Top comments (0)