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

86
Visualizações
Async/Await with setTimeout works well but not with custom delay

When I run an example that I found on the internet which uses setTimeout, it works fine. But when I replace setTimeout with a long running for loop the output appears after delay. Do we have to use a factory made asynchronous function all the time?

Original code:

const doSomethingAsync = () => {
    return new Promise(resolve => {
        setTimeout(() => resolve('I did something'), 3000)})
        }

    const doSomething = async () => {
        console.log(await doSomethingAsync())
    }
console.log('Before')
doSomething()
console.log('After')

Code with custom delay:

const doSomethingAsync = () => {
    return new Promise(resolve => {
        for(let i=0;i<4000000000;i++){}
        resolve("I did something!");
        })
        }

    const doSomething = async () => {
        console.log(await doSomethingAsync())
    }
console.log('Before')
doSomething()
console.log('After')

When the custom code runs the output of After happens after the delay, whereas in the original code After appears immediately.

Edit: By the way the question at Why isn't Javascript async function immediately returning? is similar but the order doesn't change in my case, timing does.

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