what is async javascript code example
Example 1: async awiat
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
Example 2: javascript async script
<script async src="script.js"></script>
Example 3: async await javascript
function hello() {
return new Promise((resolve,reject) => {
setTimeout(() => {
resolve('I am adam.');
}, 2000);
});
}
async function async_msg() {
try {
let msg = await hello();
console.log(msg);
}
catch(e) {
console.log('Error!', e);
}
}
async_msg();
Example 4: script async syntax
<script src="demo_async.js" async></script>
Example 5: 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 6: async await
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
alert(err);
}
}
f();