<aside>
馃挕 Con el try...catch
podemos hacer que async/await
espere a varios llamados a la vez.
</aside>
const anotherFunction = async () => {
try {
// ...
} catch {
// ...
}
}
try
resolve
.{}
聽las cuales se deben utilizar siempre, incluso para un bloque de una sola sentencia.catch
catch
聽es opcional (como hac铆amos con聽reject) y contiene sentencias que especifican que hacer si una excepci贸n es lanzada en el bloque聽try
.En este clase realizaremos el mismo challenges hecho en clases anteriores pero con funciones as铆ncronas.
Como sabemos empezamos importando fetch
y la url de la API
.
import fetch from 'node-fetch';
const API = '<https://api.escuelajs.co/api/v1>';
Realizamos la funci贸n fetchData
con async
y utilizamos await
al momento de usar fetch
debido a que es una promesa que queremos esperar a que se resuelva e igualmente con response.json()
.
async function fetchData(urlApi) {
const response = await fetch(urlApi);
const data = await response.json();
return data;
}
En otra funci贸n as铆ncrona anotherFn
realizamos los llamados a trav茅s de fetchData
de la informaci贸n que hicimos en challeges anteriores. Luego mostramos en consola.
const anotherFn = async (urlApi) => {
try {
const products = await fetchData(`${urlApi}/products`);
const product = await fetchData(`${urlApi}/products/${products[0].id}`);
const category = await fetchData(
`${API}/categories/${product.category.id}`
);
console.log(products[0]);
console.log(product.title);
console.log(category.name);
} catch (error) {
console.error(error);
}
};
<aside>
馃挕 Dentro de un try...catch
para captar el error de todas las promesas realizadas.
</aside>
Al ejecutar deber铆a mostrarnos las peticiones.
anotherFn(API);
{
id: 2,
title: 'Rustic life',
price: 469,
description: "Boston's most advanced compression wear technology increases muscle oxygenation, stabilizes active muscles",
category: {
id: 3,
name: 'Furniture',
image: '<https://api.lorem.space/image/furniture?w=640&h=480&r=3214>'
},
images: [
'<https://api.lorem.space/image/furniture?w=640&h=480&r=416>',
'<https://api.lorem.space/image/furniture?w=640&h=480&r=8744>',
'<https://api.lorem.space/image/furniture?w=640&h=480&r=2353>'
]
}
Rustic life
Furniture