user2024080
user2024080

Reputation: 5101

Needs the clarity about async function

I am trying to get the value from setTimeout. but console gives no result. how to handle this async functions? can any one help me to understand this in right way?

here is my try:

async function getTheme() {
    const value = 'abc'
    setTimeout(() => {
        return value;
    }, 3000);
}

getTheme().then(time => console.log(time)); //getting no result.

Upvotes: 1

Views: 156

Answers (1)

Terry
Terry

Reputation: 66103

That is because you're returning inside the setTimeout callback, which does not actually resolve the promise.

What you want is to instead return a promise instead:

function getTheme() {
    const value = 'abc'

    return new Promise(resolve => {
        setTimeout(() => resolve(value), 3000);
    })
}

There is no need to use async, since you are already returning a promise in the getTheme() function.

Of course, you can abstract the whole "waiting" logic into another function: then, you can keep the async if you wish:

function sleep(duration) {
    return new Promise(resolve => setTimeout(resolve, duration));
}

async function getTheme() {
    const value = 'abc';

    await sleep(3000);

    return value;
}

Upvotes: 6

Related Questions