JS-4
JS-4
async aur await ko asynchronous operations ko handle karne ke liye use kiya jata hai. Yeh
functions ko synchronous-like flow mein likhne mein madad karte hain, jo code ko padhne
aur samajhne mein easy banata hai. Use cases:
Question 2: What is the reason behind writing await inside async function only?
await keyword sirf async function ke andar hi use ho sakta hai kyunki await ka kaam
asynchronous operations ko pause karna aur result ko wait karna hota hai bina event loop ko
block kiye. async function ensure karta hai ki function promise return kare, jo asynchronous
behavior ko manage karne mein help karta hai.
javascript
Copy code
async function fun1() {
console.log('a');
console.log('b');
await setTimeout(() => console.log('c'), 1000);
await setTimeout(() => console.log('d'), 0);
console.log('e');
}
fun1();
css
Copy code
a
b
e
c
d
Question 4: Can you solve the above problem, so that we get proper outputs? Hint:
await should work properly.
setTimeout ko promise mein wrap karna hoga taaki await properly kaam kare:
javascript
Copy code
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
fun1();
css
Copy code
a
b
c
d
e
Question 5: What are callbacks? What is callback hell? Can you give an example of
callback hell?
• Callbacks: Ek function jo dusre function ko argument ke roop mein pass kiya jata hai
aur operation complete hone par call kiya jata hai.
• Callback Hell: Nested callbacks ka issue jab multiple asynchronous operations ko
sequence mein handle kiya jata hai, jo code ko complex aur hard to manage banata
hai.
javascript
Copy code
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log(finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
Question 6: How are promises more superior than callbacks? How do promises solve
the issue of callback hell?
• Promises vs Callbacks:
o Promises neater aur more readable code provide karte hain.
o Error handling catch block ke through simplified hota hai.
o Promises chaining allow karte hain jo sequential asynchronous operations ko
easier banata hai.
• Solving Callback Hell with Promises: Promises chaining se nested callbacks ko
avoid kar sakte hain:
javascript
Copy code
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(finalResult))
.catch(error => console.error(error));
Yeh approach code ko linear aur readable banata hai, jo callback hell ko effectively solve
karta hai