aaaidan
aaaidan

Reputation: 315

How do you only execute if the promise was fulfilled?

I'm using promises to force NodeJS to stop running if certain functions do not execute as required. At the moment, the server stops as required but I would also like to include a console log if the functions successfully fulfilled their promises. I'm using the npm 'q' module.

Working code

Q.all([
    someFunction1(),
    someOtherFunction('https://www.google.com', 'Google'),
    someOtherFunction('https://www.facebook.com', 'Facebook'),
])
    .catch(function (err){
        console.log(err);
        process.exit(1);
})

When adding a then as per below, the then executes before the promises has been completed and therefore the console.log call is executed regardless of whether the promise is fulfilled or rejected.

Q.all([
    someFunction1(),
    someOtherFunction('https://www.google.com', 'Google'),
    someOtherFunction('https://www.facebook.com', 'Facebook'),
])
    .then(console.log("No problem here"))
    .catch(function (err){
        console.log(err);
        process.exit(1);
})

Upvotes: 5

Views: 1358

Answers (1)

sdgluck
sdgluck

Reputation: 27217

You are calling console.log in-place, so it is invoked regardless of whether the promise succeeds or fails.

Pass a function to .then that contains the log as a statement, and this only will be invoked on success of Q.all(...):

.then(function () {
    console.log("No problem here");
})

Upvotes: 6

Related Questions