Skip to content

Instantly share code, notes, and snippets.

@whal-e3
Created November 15, 2020 04:58
Show Gist options
  • Save whal-e3/1a31ff5dc5b159deaf20953e904c9a97 to your computer and use it in GitHub Desktop.
Save whal-e3/1a31ff5dc5b159deaf20953e904c9a97 to your computer and use it in GitHub Desktop.
JS async & await
async function myFunc() {
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Hello'), 1000);
});
const err = false;
if (!err) {
const res = await promise; // wait until promise is resolved
return res;
} else {
await Promise.reject(new Error('something went wrong'));
}
}
myFunc()
.then(res => console.log(res))
.catch(err => console.log(err));
// ------------------------------------------------------------------------------
async function getUsers() {
// await reponse of the fetch call
const response = await fetch('https://jsonplaceholder.typicode.com/users');
// Only proceed after response resolved
const data = await response.json();
// Only proceed after data resolved
return data;
}
getUsers().then(users => {
console.log(users);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment