proper way to write async await function javascript code example
Example 1: async await in forloops
// Series loop
async (items) => {
for (let i = 0; i < items.length; i++) {
// for loop will wait for promise to resolve
const result = await db.get(items[i]);
console.log(result);
}
}
// Parallel loop
async (items) => {
let promises = [];
// all promises will be added to array in order
for (let i = 0; i < items.length; i++) {
promises.push(db.get(items[i]));
}
// Promise.all will await all promises in the array to resolve
// then it will itself resolve to an array of the results.
// results will be in order of the Promises passed,
// regardless of completion order
const results = await Promise.all(promises);
console.log(results);
}
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(); //output - I am adam.
Example 4: async await cacurios animal
// Verifying a user with async/await
const verifyUser = async function(username, password){
try {
const userInfo = await dataBase.verifyUser(username, password);
const rolesInfo = await dataBase.getRoles(userInfo);
const logStatus = await dataBase.logAccess(userInfo);
return userInfo;
}catch (e){
//handle errors as needed
}
};
// Here we use the same `database.verifyUser`, `database.getRoles`
// and `database.logAccess` implementation based on promises