cib
cib

Reputation: 2414

How to combine Promises with if?

In the following example, I would like to conditionally execute somePromise, then regardless of the condition execute anotherPromise.

if (somecondition) {
    somePromise().then((args) => { ... } );
}

// Not waiting for somePromise() here, but it should.
return anotherPromise().then((args) => {
    muchmorecodehere;
}

The only way I can think of right now is to turn the last part into a function and execute it in both branches, but that seems very cumbersome. Surely I'm doing something wrong?

let helperFunction = () => {
    return anotherPromise().then((args) => {
        muchmorecodehere;
    }
}

if (somecondition) {
    return somePromise().then((args) => { ... } ).then(helperFunction);
}

return helperFunction;

Upvotes: 1

Views: 112

Answers (3)

cib
cib

Reputation: 2414

Another way to get around the problem, is to just wrap the initial if in a then block by chaining it to a Promise.resolve().

return Promise.resolve().then(() => {
    if (somecondition) {
        return somePromise().then((args) => { ... } );
    }
}).then(() => {
    return anotherPromise();
}).then((args) => {
    //muchmorecodehere
});

Upvotes: 0

JLRishe
JLRishe

Reputation: 101680

You can take advantage of the fact that .then() returns a new promise and chain off either that or a dummy promise:

var nextPromise = somecondition
    ? somePromise.then((args) => { ... })
    : Promise.resolve();

return nextPromise.then(() => anotherPromise)
    .then((args) => {
        // muchmorecodehere
    });

Upvotes: 2

Andrea
Andrea

Reputation: 3440

You can create a default, already resolved, promise (lets call it conditionalPromise), for the conditional part and always chain this promise with anotherPromise.

If someCondition is false then conditionalPromise is an already resolved promise and it can be safely chained to anotherPromise.

If someCondition is true then somePromise is assigned to conditionalPromise and when it will be resolved, then anotherPromise will be executed.

conditionalPromise = Promise.resolve(); // Create a default, already resolved, promise
if (someCondition) {
    // Assign somePromise to conditionalPromise, overwriting the default one
    conditionalPromise = somePromise
}

// Now chain the 2 promises
return conditionalPromise.then((args) => { 
    anotherPromise.then((args) => {
        muchmorecodehere;
    }
});

Upvotes: 1

Related Questions