Site icon i2tutorials

Javascript-async

Javascript-async

 

The async keyword  placed before a function, makes the function return a promise:

 

async function f() {
 return Hello;
}

 

Is the same as:

 

async function myFunction() {
 return Promise.resolve("Hello");
}

 

use the Promise:

 

myFunction().then(
 function(value) { /* code if successful */ },
 function(error) { /* code if some error */ }
);

 

Example:

 

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript async / await</h2>

<p id="i2"></p>

<script>
function myDisplayer(some) {
 document.getElementById("i2").innerHTML = some;
}

async function myFunction() {return "Hello";}

myFunction().then(
 function(value) {myDisplayer(value);},
 function(error) {myDisplayer(error);}
);</script>

</body>
</html>

 

OUTPUT:

 

JavaScript async / await
Hello

 

 

 

Exit mobile version