SB2055
SB2055

Reputation: 12862

Conditionally chaining promises - how to avoid code duplication?

I have the following:

if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseMakerB(someLongListOfArguments);
     });
}
else
    return promiseMakerB(someLongListOfArguments);

How can I eliminate that code repetition (promiseMakerB)?

Upvotes: 0

Views: 47

Answers (2)

Jaromanda X
Jaromanda X

Reputation: 1

you can do the following, however, it's not necessarily the most readable way of doing so

return (someCondition ? promiseMakerA(): Promise.resolve()).then(function() { 
    return promiseMakerB(someLongListOfArguments); 
});

Upvotes: 3

charlietfl
charlietfl

Reputation: 171669

Assuming arguments are the same in each condition for promiseB store it in a variable first ... then return that variable where applicable

let promiseB = promiseMakerB(someLongListOfArguments);

if (someCondition) {
     return promiseMakerA().then(function() {
         return promiseB;
     });
}
else
    return promiseB;

Upvotes: 1

Related Questions