Interview question
How does async/await simplify working with Promises? async/await Promises के साथ काम करना कैसे simplify करता है?
Answer
async/await is syntactic sugar over Promises that lets asynchronous code be written and read like synchronous code, avoiding long .then() chains.
// Promise chain version
function getUserData(id) {
return fetchUser(id)
.then(user => fetchOrders(user.id))
.then(orders => {
console.log('Orders:', orders);
return orders;
})
.catch(error => console.log('Error:', error));
}
// async/await version - reads top to bottom, like sync code
async function getUserData(id) {
try {
const user = await fetchUser(id);
const orders = await fetchOrders(user.id);
console.log('Orders:', orders);
return orders;
} catch (error) {
console.log('Error:', error);
}
}
// Key facts:
// 1. 'async' before a function makes it always return a Promise
async function greet() {
return 'Hello'; // automatically wrapped: Promise.resolve('Hello')
}
greet().then(msg => console.log(msg)); // Hello
// 2. 'await' can only be used inside an async function
// 3. 'await' pauses execution until the Promise settles, without blocking the thread
async function demo() {
console.log('Start');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('After 1 second'); // runs after pause, other code can run meanwhile
}
demo();
console.log('This runs before "After 1 second"');async/await Promises के ऊपर syntactic sugar है जो asynchronous code को synchronous code जैसा लिखने और पढ़ने देता है।
// Promise chain
function getUserData(id) {
return fetchUser(id)
.then(user => fetchOrders(user.id))
.then(orders => {
console.log('Orders:', orders);
return orders;
})
.catch(error => console.log('Error:', error));
}
// async/await version
async function getUserData(id) {
try {
const user = await fetchUser(id);
const orders = await fetchOrders(user.id);
console.log('Orders:', orders);
return orders;
} catch (error) {
console.log('Error:', error);
}
}
// 'async' function हमेशा Promise return करता है
async function greet() {
return 'Hello'; // Promise.resolve('Hello')
}
greet().then(msg => console.log(msg)); // Hello
// 'await' Promise settle होने तक pause करता है, blocking नहीं
async function demo() {
console.log('Start');
await new Promise(resolve => setTimeout(resolve, 1000));
console.log('After 1 second');
}
demo();
console.log('यह पहले चलेगा');Was this answer clear?