async await es6 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() {
// read our JSON
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
// read github user
let githubResponse = await fetch(`https://api.github.com/users/${user.name}`);
let githubUser = await githubResponse.json();
// show the avatar
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
// wait 3 seconds
await new Promise((resolve, reject) => setTimeout(resolve, 3000));
img.remove();
return githubUser;
}
showAvatar();
Example 3: how to make an async function
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
//async function:
async function asyncCall() {
console.log('calling');
const result = await resolveAfter2Seconds();
console.log(result);
// expected output: 'resolved'
}
asyncCall();
Example 4: js async await
/* Notes:
1. written like synchronous code
2. compatible with try/catch blocks
3. avoids chaining .then statements
4. async functions always return a promise
5. function pauses on each await expression
6. A non promise value is converted to
Promise.resolve(value) and then resolved
*/
// Syntax
// Function Declaration
async function myFunction(){
await ... // some code goes here
}
// Arrow Declaration
const myFunction2 = async () => {
await ... // some code goes here
}
// OBJECT METHODS
const obj = {
async getName() {
return fetch('https://www.example.com');
}
}
// IN A CLASS
class Obj {
// getters and setter CANNOT be async
async getResource {
return fetch('https://www.example.com');
}
}
Example 5: async await .catch
function getQuote() {
let quote = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
return quote;
}
async function main() {
try {
var quote = await getQuote();
console.log(quote);
} catch (error) {
console.error(error);
}
}
main();
Example 6: async await
async function showAvatar() {
// read
await setTimeout(resolve, 3000);
// read next 3s
}
showAvatar();