Promise.resolve() returns a weird result when in setTimeout()

1.

let f = Promise.resolve(15);
console.log(f);

f.then(v => console.log(v));

Result:

[object Promise] { ... }
15

Everything works perfectly as thought ... but when I plug it inside a setTimeout() function I am not able to reason why the result is 1 ...

2.

let f = Promise.resolve(setTimeout(() => Promise.resolve(15), 1000));
console.log(f);

f.then(v => console.log(v));

Result:

[object Promise] { ... }

1

Thanks!

Upvotes: 0

Views: 47

Answers (2)

ngr900
ngr900

Reputation: 109

What you're seeing returned is the setTimeout's timeoutID, a number assigned by the browser to track all the separate setTimeout calls.

The mistake you're making is here:

let f = Promise.resolve(setTimeout(() => Promise.resolve(15), 1000));

You're creating a Promise that instantly resolves using Promise.resolve and making it instantly resolve with setTimeout(() => Promise.resolve(15), 1000). This is probably the first timeout within the script, which is why the timeoutID is 1.

You want the promise to resolve with 15, not setTimeout[...]. What you should do to achieve the result you're aiming for is this:

let f = new Promise(resolve => setTimeout(() => resolve(15), 1000));

That is, create a new Promise that starts a new setTimeout which runs after 1000ms and resolves the containing Promise.

Upvotes: 1

Quentin
Quentin

Reputation: 943470

setTimeout does nothing with the return value of the callback function you pass it. Putting a resolved promise there is entirely irrelevant.

The resolved value of the outer promise is the return value of setTimeout.

The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

MDN


If you want to resolve a promise after some time then use a normal promise constructor.

const promise = new Promise(
    (res) => {
        const resolve = () => res(15);
        setTimeout(resolve, 1000);
    }
);

promise.then( value => console.log(value) );

Upvotes: 1

Related Questions