Home > other >  Building async with setTimeout like a promise with setTimeout doesn't work
Building async with setTimeout like a promise with setTimeout doesn't work

Time:11-09

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 ?

CodePudding user response:

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,
    )
}

CodePudding user response:

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.

  • Related