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

87
Vistas
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 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