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?

asked Sep 7, 2017 at 8:21
\$\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();
 });
}
answered Sep 7, 2017 at 9:11
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.