2
\$\begingroup\$

I am writing a function in Typescript that involves checking a condition, doing some extra processing if the condition is satisfied, and then doing the bulk of the job.

Here's the catch: the extra processing stuff, that runs if the condition is satisfied, returns a promise. So instead of a clean, simple solution like this:

function openDoor(door) {
    if(door.locked) {
        door.unlock();
    }
    door.handle.turn();
    door.handle.push();
}

It turns into some horrible mess, like this:

function openDoor(door) {
    if(door.locked) {
        door.unlock().then(() => {
            door.handle.turn();
            door.handle.push();
        });
    } else {
        door.handle.turn();
        door.handle.push();
    }
}

Why, you ask?

Unlocking the door takes some time, and I can't turn and push the handle until it's done. Without code duplication, I wouldn't have time to unlock the door before pushing it.

So how can I make this better?

In the shortened example above, the duplicated section is quite small, but troublesome nonetheless. I would like to be able to make changes in a single place rather than two, when I update the code. So, how can I avoid code duplication while keeping my Promise?

\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

You could move the door.locked check into the door.unlock() function (or into a new function) which would allow you return a promise for both cases:

function unlockDoor(door) { 
   return door.locked 
          ? door.unlock()
          : Promise.resolve();
   }  
}

function openDoor(door) {
    unlockDoor(door).then(() => {
            door.handle.turn();
            door.handle.push();
        });
}
\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.