javascript make a function async code example
Example 1: how to make an async function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
Example 2: javascript async script
<script async src="script.js"></script>
Example 3: script async syntax
<script src="demo_async.js" async></script>
Example 4: javscript async await explained
function getJSON(){
return new Promise( function(resolve) {
axios.get('https://tutorialzine.com/misc/files/example.json')
.then( function(json) {
resolve(json);
});
});
}
async function getJSONAsync(){
let json = await axios.get('https://tutorialzine.com/misc/files/example.json');
return json;
}
Example 5: async and await
function delayResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve(‘Done’);
}, 5000)
})
}
async function getResult() {
let result = await delayResult();
return result;
}
getResult();