user51
user51

Reputation: 10143

chained promises in nodejs is executing only the first promise but not chained promises

I have below code in nodejs. I have two promises chained and then by console message done at the end.

    const myPromisedFunction = () => {
        console.log('my promised function');
        return new Promise((resolve, reject) => {
            setTimeout(() => resolve, 1000);
        });
    };


    myPromisedFunction().then(() => myPromisedFunction()).then(() => console.log('done'));

when I run the program I get output as my promised function only once. But I expect twice followed by done message.

node version I'm using is v.8.15.0

Any idea what is wrong in my code?

Upvotes: 0

Views: 27

Answers (2)

OlegDovger
OlegDovger

Reputation: 122

Or you can do it even simplier

const myPromisedFunction = () => {
    console.log('my promised function');
    return new Promise((resolve, reject) => {
        setTimeout(resolve, 1000);
    });
};


myPromisedFunction().then(myPromisedFunction).then(() => console.log('done'));

Use resolve instead of () => resolve and myPromisedFunction instead of () => myPromisedFunction

Upvotes: 1

CaKa
CaKa

Reputation: 3779

resolve() instead of resolve in the setTimeoutFn

Upvotes: 3

Related Questions