Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda