Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ?

>Solution :

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,
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading