Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise not waiting to finish

I looked at many examples today. They seem to suggest that the following code should be executed in chain:

let f = () => {
    return new Promise((res, rej) => {
        console.log('entering function');
        setTimeout(() => {
            console.log('resolving');
            res()
        }, 2000)
    });
};

Promise.resolve()
    .then(f())
    .then(f());

Expected output would be:

entering function
resolving
entering function
resolving

But it isn't. The output is

entering function
entering function
resolving
resolving

and I can't figure out why. Any help will be much appreciated.

like image 275
Adam Avatar asked Dec 05 '25 06:12

Adam


1 Answers

try then(f) instead of then(f())

then expects a function.

you can also do then(()=>f())

like image 132
JJJ Avatar answered Dec 07 '25 19:12

JJJ