Asynchronous function is a function preceded by the word "async" and that returns a promise. When it happens that the returned value is not a promise, it will be considered as a resolved promise.
<script type="text/javascript">
async function myFunction(){
return Promise.resolve('Working');
}
let myFunction2 = async () => {
myFunction.then(resp => console.log(resp));
};
</script>
Within an asynchronous function you can use "await", which has the objective of freezing the execution of this asynchronous function until the promise inside it is resolved.
Any function that returns a promise can be used to await.
In the following script we create an asynchronous function that has a delay of 2 seconds until the promise ends, by making use of "await", the function will not be executed until the promise ends. While the other functions arranged in the script will be executed.
<script>
async function myFunction() {
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Ready'), 2000);
});
let myResult = await myPromise;
alert(myResult);
}
myFunction();
setTimeout(console.log('hello'), 500);
console.log('now');
</script>
Tips on SEO and Online Business
Next Articles
Previous Articles