Skip to content

Instantly share code, notes, and snippets.

@programadorabordo
Created August 25, 2020 02:03
Show Gist options
  • Save programadorabordo/280555ad6660b5de681c40da708059e7 to your computer and use it in GitHub Desktop.
Save programadorabordo/280555ad6660b5de681c40da708059e7 to your computer and use it in GitHub Desktop.
Código da aula ao vivo sobre async await https://youtu.be/mTLg2qd9r0M
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Async Await | JS Day | Programador a Bordo</title>
</head>
<body>
<script>
/* request.get('http://site.com', function(resultado) {
request.get(`http://site.com/resultado.id`, function(resultado2) {
request.get(`http://site.com/${resultado.id}/${resultado2.id}`, function(resultado2) {
})
})
}) */
/* request.get('http://site.com')
.then(resultado => {
return request.get()
})
.then() */
// async await
/* function getPosts() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(function(d) {
return d.json()
})
.then(console.log)
} */
async function getPosts() {
const result = await fetch('https://jsonplaceholder.typicode.com/posts');
return result.json();
}
/* getPosts().then(console.log);
console.log('VALOR PRIMEIRO'); */
/* (async function(){
const posts = await getPosts();
console.log(posts);
}()) */
/* async function getNumero() {
return await 2;
}
function getNumero() {
return Promise.resolve(2);
}
getNumero().then(function(resultado) {
console.log(resultado);
})
(async function(){
const numero = await getNumero();
console.log(numero);
}()) */
async function getUsers() {
const result = await fetch('https://jsonplaceholder.typicode.com/users');
return result.json();
}
async function getUserPosts(userId) {
const posts = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}/posts`);
return posts.json();
}
(async function() {
const users = await getUsers();
const posts = [];
/* for (let i = 0; i < users.length; i++) {
posts.push(await getUserPosts(users[i].id))
} */
/* for (let i = 0; i < users.length; i++) {
posts.push(getUserPosts(users[i].id))
} */
/* const allPosts = await Promise.all(posts);
console.log(allPosts); */
// Promise.all(posts).then(console.log)
/* const result = await Promise.all(users.map(u => getUserPosts(u.id)))
console.log(result); */
} ())
(async function() {
try {
// Promise
/* fetch('https://jsonplaceholder.typicode.com/users')
.then(function(d) {
return JSON.parse(d);
})
.catch(function(e) {
console.log('ERRO NA PROMISE', e)
}) */
const users = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await users.json();
console.log(data);
} catch(e) {
console.log('ERRO AQUI NO CATCH');
}
}())
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment