Volver a Asincronía
Asincronía — Leccion 2
·20 minAsync/Await
Escribe codigo asíncrono que parece síncrono.
Async/Await
async/await es azúcar sintáctico sobre Promises.
typescript
async function obtenerUsuario(id: number) {
const res = await fetch(`/api/users/${id}`);
const usuario = await res.json();
return usuario;
}
Manejo de errores
typescript
async function funcionSegura() {
try {
const datos = await fetch("/api/datos");
return await datos.json();
} catch (error) {
console.error("Error:", error);
return null;
}
}
Paralelismo
typescript
// Secuencial (lento)
const a = await funcionA();
const b = await funcionB();
// Paralelo (rapido)
const [a, b] = await Promise.all([
funcionA(),
funcionB(),
]);
Async en loops
typescript
// For...of con await
for (const id of ids) {
const usuario = await fetch(`/api/users/${id}`);
console.log(await usuario.json());
}
// forEach NO funciona con await
ids.forEach(async id => {
// Esto no espera
});
Retornar valores
typescript
async function obtenerDatos() {
// async siempre retorna Promise
return { nombre: "Ana" }; // Promise<{ nombre: string }>
}
const datos = await obtenerDatos(); // { nombre: "Ana" }
Ejercicio pratico
Convierte una función con Promises a async/await.
exercise.ts
Loading...
Resultado
Haz clic en "Ejecutar" para ver el resultado...