A function that is declared with the async keyword returns a Promise .
Within an async function, the await function waits for a Promise to be resolved before moving on to the next line of code.
Async will call code asynchronously and await make it wait for promise to get resolved .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <p id="div1"></p> <br /> <p id="div2"></p> <script type="text/javascript"> function display(data) { document.getElementById("div1").innerHTML = data; } // dummy api call function fetchIt() { return "Shrikant"; } let startCall = async () => { let res = await fetchIt(); // waiting for fetchIt response let value = await res; // waiting for response display(value) } startCall(); // execution starts </script> </body> </html> |
Output: Shrikant
In above example , startCall method gets invoke which asynchronously call the fetchIt function .
 it will wait for getting success or fail response. once returned success , the value is  set to  paragraph element in HTML.