ES5
function myFunc(){
return 'Hello';
}
console.log(myFunc());
Async
async function myFunc(){
return 'Hello';
}
myFunc()
.then(res => console.log(res))
async function myFunc(){
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Hello'), 1000);
});
const error = false;
if(!error){
// Wait until promise is resolved
const res = await promise;
return res;
} else{
await Promise.reject(new Error('Something went wrong'));
}
}
myFunc()
.then(res => console.log(res));
async function getUsers(){
// Await response of the fetch call
const response = await fetch('https://jsonplaceholder.typicode.com/users');
// Only proceed when its resolved
const data = await response.json();
// Only proceed when the second promise is resolved
return data;
}
getUsers().then(users => console.log(users));
Leave a Reply