xxxxxxxxxx
# async await function
import asyncio
import time
async def sleep_6():
time.sleep(5)
print('5 done')
time.sleep(3)
print('3 done')
async def sleep_8():
await asyncio.sleep(7)
print('8 done')
async def gather_fxn():
await asyncio.gather(sleep_6(), sleep_8())
loop=asyncio.new_event_loop()
loop=loop.run_until_complete(gather_fxn())
loop.close()
# output:
# 5 done
# 3 done
# 8 done
xxxxxxxxxx
// example using promise
const user = () => {
fetch("https://randomuser.me/api/?results=1")
.then((data) => {
console.log(data); // here you recive data
}).catch((err)=>{
console.log(err); // here error
});
}
// example using async/await
const user = async () => {
// you must have use async keyword before use await
const data = await fetch("https://randomuser.me/api/?results=1");
console.log(data); // if error occured it will be null or empty
}
xxxxxxxxxx
// Old School Javascript Invoke
(async function() {
await someAsyncFunction();
})();
//New ES6 Javascript Invoke
(async () => {
await someAsyncFunction();
})();
//Example (async & await)
function delayResult() {
return new Promise(resolve => {
setTimeout(() => {
resolve(‘Done’);
}, 5000)
})
}
async function getResult() {
let result = await delayResult();
return result;
}
getResult();
//New Example
const data = async () => {
const got = await fetch('https://jsonplaceholder.typicode.com/todos/1');
console.log(await got.json())
}
data();
xxxxxxxxxx
//used in node.js
const fetch = require('node-fetch');
async function Showuser() {
const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
const date = await result.json();
console.log(date);
}
Showuser();
xxxxxxxxxx
const yourAsyncFunction = async () => {
// do something asynchronously and return a promise
return result;
}
anArray.forEach(async item => {
// do something asynchronously for each item in 'anArray'
// one could also use .map here to return an array of promises to use with 'Promise.all()'
});
server.getPeople().then(async people => {
people.forEach(person => {
// do something asynchronously for each person
});
});
xxxxxxxxxx
async function showAvatar() {
// read
await setTimeout(resolve, 3000);
// read next 3s
}
showAvatar();
xxxxxxxxxx
async function f() {
try {
let response = await fetch('/no-user-here');
let user = await response.json();
} catch(err) {
// catches errors both in fetch and response.json
alert(err);
}
}
f();
xxxxxxxxxx
async function run () {
const user = await getUser()
const tweets = await getTweets(user)
return [user, tweets]
}
xxxxxxxxxx
async function () {
const fetchAPI = fetch(`https://bn-hadith-api.herokuapp.com/hadiths/0`);
const response = await fetchAPI;
const data = await response.json();
console.log(data);
}
xxxxxxxxxx
// ASYNC will always returns promises
// NOTE : AWAIT should be kept only inside ASYNC function
// AWAIT can't be used in regular function
/* TIPS : Js is single threaded & synchronous in nature BUT, we can
make it as asyncronous by using (ASYNC/AWAIT)*/
//(Example 1 : fetching Random Image)
async function RandomImage(){ //remember async and await is powerful for async operations, always await should be inside of async only.
try {
const raw_response = await fetch("https://www.themealdb.com/api/json/v1/1/random.php");
if (!raw_response.ok) { // check for the 404 errors
throw new Error(raw_response.status);
}
const json_data = await raw_response.json(); //AWAIT
let data = json_data.meals[0];
console.log(data);
}
catch (error) { // catch block for network errors
console.log(error);
}
}
RandomImage();
//(Example 2 : returning another promise)
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");
xxxxxxxxxx
async function abc() {
console.log("1");
const response = await fetch("https://jsonplaceholder.typicode.com/users");
console.log("4");
const users = await response.json();
console.log("5");
return users;
}
const a = abc();
a.then((e) => {
console.log(e);
});
console.log("2");
console.log(a);
console.log("3");