Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

154
Vistas
How to avoid then when calling a async function

I often read that async/await is better than .then(). I learned, to use await, I need an async function. To handle errors, I need try/catch. So I built this simple get request:

const isAvailable = async (url) => {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (err) {
        console.error(err);
    }
};
const fetchedData = isAvailable("/api");
console.log(fetchedData); // Returns: Promise {status: "pending"}

When I see this, it is somehow logical for me, but I can't really understand it. fetch() returns a Promise, thus fetchedData is a Promise. But the try block shout return an object, thus fetchedData should be a Promise. Even when I see this, it is somehow logical for me, but I can't really understand it, either. fetchedData is a pending Promise and should be awaited as well, so I tried:

const fetchedData = await isAvailable("/api"); //SyntaxError: Unexpected identifier 'isAvailable'. Expected ';' after variable declaration.
console.log(fetchedData); 

I'd say this is because I call await without being in an async function, so I ended with:

isAvailable("/api").then((fetchedData) => {
    console.log(fetchedData);
});

But now I'm back to .then() what I want to avoid in my exercise.

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda