await function javascript code example
Example 1: async await catch error
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
alert(err);
}
}
Example 2: async awiat
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
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: 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 5: js await
const a = async () => {
await b();
c();
};
Example 6: await javascript
The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.