Table of Contents
hide
Async
Async Keyword के जरिये एक function को async function बनाया जाता है |
Async Function हमेसा एक promise return करता है |
promise में आ रहे complication को हटाने के लिए async function को बनाया गया है |
इसे javascript 2017 version में डाला गया है |
javascript में promises को आसानी से इस्तेमाल करने के लिए और इसका code ज्यादा simple बनाने के लिए async और await को किया गया है |
Await
await keyword async function के अन्दर काम करता है |
Await javascript codes को wait कराके रखता है जब तक की सारे promises settled हो ना जाये और result return कर ना दें |
नॉटपॉइंट: await keyword हमेसा async function के साथ उपयोग होता है |
Async Function का उदाहरण
<!DOCTYPE html>
<html>
<head>
<title>javascript async function example</title>
</head>
<body>
<script>
function asynFunction1(){
let promise1 = new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log("1st promise get resolved");
resolve("value1");
},1*1000)
});
let promise2 = new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log("2nd promise get resolved");
resolve("value2");
},2*1000)
});
let combineCall = Promise.all([promise1,promise2]);
return combineCall;
}
async function showData() {
let data = await asynFunction1();
console.log(data);
}
showData();
</script>
</body>
</html>
output
