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

230
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
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