1

I'm wondering how I can prevent copying code in the following code. I copied the function wishModel.createWish(). The reason to copy the code is:

  • in the if-part the function must be triggered after a promise (a modal is opened) is resolved
  • in the else-part the function is executed immediately

Thanks for helping me improve my code!

    if (copyExistsOnList) {
        var copyWarningPopup = $uibModal.open({...});

        copyWarningPopup.result.then(function (wish) {
            wishModel.createWish(newWish, userID, userID, wish._id);
        });
    } else {
        wishModel.createWish(newWish, userID, userID, wish._id);
    }
bits
  • 672
  • 2
  • 7
  • 26

2 Answers2

5

You can make an immediately resolving promise for the second case, and then you always have a promise you can chain the final then to:

(copyExistsOnList ? $uibModal.open({...}).result : Promise.resolve(wish))
    .then(function (wish) {
        wishModel.createWish(newWish, userID, userID, wish._id);
    });
trincot
  • 317,000
  • 35
  • 244
  • 286
1

Your code uses variable shadowing on wish: there's one declaration as part of the function signature, and another in an outer scope which you haven't shown (or else using the global namespace). This means there are two completely separate variables. Some people consider this bad practice, since it's possible to accidentally write code in the inner scope without realising that you're using the inner declaration. But I'm going to assume that's what you intended.

function createWish(wish) {
    wishModel.createWish(newWish, userID, userID, wish._id);
}

if (copyExistsOnList) {
    var copyWarningPopup = $uibModal.open({...});
    copyWarningPopup.result.then(createWish);
} else {
    createWish(wish);
}
David Knipe
  • 3,417
  • 1
  • 19
  • 19
  • Thanks for the warning! But like you said: it's intended. I want to be able to write code in the inner scope without affecting the outer scope. – bits Jan 14 '18 at 09:59