Javascript:使用 Promise 时需要帮助防止代码重复

bit*_*its 1 javascript promise

我想知道如何防止复制以下代码中的代码。我复制了这个函数wishModel.createWish()。复制代码的原因是:

  • 在 if 部分中,必须在解决 Promise(打开模式)后触发该函数
  • 在 else 部分,函数立即执行

感谢您帮助我改进我的代码!

    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);
    }
Run Code Online (Sandbox Code Playgroud)

tri*_*cot 5

您可以为第二种情况做出立即解决的承诺,然后您总是有一个可以将最终的承诺链接then到:

(copyExistsOnList ? $uibModal.open({...}).result : Promise.resolve(wish))
    .then(function (wish) {
        wishModel.createWish(newWish, userID, userID, wish._id);
    });
Run Code Online (Sandbox Code Playgroud)