简体   繁体   中英

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 )?

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); 
});

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM