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

296
Visualizações
Svelte / Vanilla JS - do I need to use .then() on awaiting an async function?

This is probably best explained with code:

in my utils file I have created the following async function:

export async function post(fetch, url, body) {
    const res = await fetch(url, {
        method: 'POST',
        body,
        headers
    });
    return await res.json();
}

I've stripped down the function to avoid posting too much code.

Now in my .svelte component file, the function above is called as followed:

async function handleLogin() {
    const result = await post(fetch, 'https://accountingserver.dev/auth/login', {
        email: email,
        password: password
    });
    console.log(result);
}

In the above example, the result is output correctly as expected. But I have found I can also do the following and get the same outcome:

async function handleLogin() {
    post(fetch, 'https://accountingserver.dev/auth/login', {
        email: email,
        password: password
    }).then((result) => {
        console.log(result);
    });
}

So my question, is any of the two methods more valid and if so .. why?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's a preference thing, but where possible you should lean towards using async/await. It makes your code cleaner and easier to read and also helps you avoid Promise Hell.

You should note that some environments might not support async/await as it is a newer feature, but most modern environments will likely natively support it. In cases where async/await is not supported, async function name(){} syntax will not be allowed and you will need to use .then() instead of await.

about 4 years ago · Juan Pablo Isaza Relatório
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