await syntax 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: 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 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: async await
async function RandomImage(){
try {
const raw_response = await fetch("https://www.themealdb.com/api/json/v1/1/random.php");
if (!raw_response.ok) {
throw new Error(raw_response.status);
}
const json_data = await raw_response.json();
let data = json_data.meals[0];
console.log(data);
}
catch (error) {
console.log(error);
}
}
RandomImage();
console.log("1 is working");
console.log("2 is working");
var AsyncFunction = async() => {
var x = new Promise((resolve,reject) => {
setTimeout(() => resolve("3 is working"), 3000);
});
var result = await x;
return result;
}
AsyncFunction().then(resolved => console.log(resolved));
console.log("3 is working");
Example 5: async function someFunction()
async function someFunction() {
console.log("someFunction");
}
Console.log("Start");
someFunction();
console.log("End");
Example 6: async await javascript
myFunction().then(
function(value) { },
function(error) { }
);