how to write an async function in javascript 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: script async syntax
<script src="demo_async.js" async></script>
Example 3: js async await
async function myFunction(){
await ...
}
const myFunction2 = async () => {
await ...
}
const obj = {
async getName() {
return fetch('https://www.example.com');
}
}
class Obj {
async getResource {
return fetch('https://www.example.com');
}
}
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: define async function in node js
async function name([param[, param[, ...param]]]) {
statements
}
Example 6: async await js
fetch('coffee.jpg')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
} else {
return response.blob();
}
})
.then(myBlob => {
let objectURL = URL.createObjectURL(myBlob);
let image = document.createElement('img');
image.src = objectURL;
document.body.appendChild(image);
})
.catch(e => {
console.log('There has been a problem with your fetch operation: ' + e.message);
});