await async node js code example
Example 1: async await
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
Example 2: async await
async function showAvatar() {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubResponse.json();
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
return githubUser;
}
showAvatar();
Example 3: nodejs promise async
function square(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(Math.pow(x, 2));
}, 2000);
});
}
async function layer(x)
{
const value = await square(x);
console.log(value);
}
layer(10);
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");