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

235
Visualizações
Building async with setTimeout like a promise with setTimeout doesn't work

On https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function they say that writing

async function foo() {
   return 1
}

is the same as writing

function foo() {
   return Promise.resolve(1)
}

So that means that if we want to 'transform' a promise into an async function, we have to replace resolve(promise_result) with return promise_result.

But when I try to use setTimeout with async it doesn't work:

const test1 = async () => {
    setTimeout(
        () => {
            return 5;
        },
        2000,
    )
}
const test2 = () => new Promise(
    (resolve, reject) => {
        setTimeout(
            () => resolve(25),
            1000
        )
    }
)

const execute = async () => {
    const result = await test1();
    console.log(result); // undefined
}

execute();

If I use await on test2 it works but it doesn't work on test1. Why is that ? Is async/await only meant to deal with pending promises without using .then or can I use async with return result instead of using Promise with resolve ?

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

0

Its undefined because test1 does not return anything back. take a closer look you return it in the anonymous function back

const test1 = async () => { // <--- this function returns nothing back. Nothing means "undefined"
    setTimeout(
        () => {       // <---- you return it here back in your anonymous  function witch makes no sense
            return 5;
        },
        2000,
    )
}
about 4 years ago · Juan Pablo Isaza Relatório

0

That's a fun one. The problem here is that

const test1 = async () => {
    setTimeout(
        () => {
            return 5;
        },
        2000,
    )
}

test1 is an async function, BUT setTimeout is not.

setTimeout will just schedule whatever you pass it and return its timeoutID immediately. In such a case, you'd really need to handle the Promise code manually.

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