javascript - 如果没有其他函数链接到 promise ,则默认行为

标签 javascript angularjs promise

我想打开一个“确认您要取消对话框”,如果没有链接其他功能,则默认导航回页面($window.history.back(); )。

如果我传递回调,我可能会这样做:

function openCancelModal(form, callback) {
     if (form.$dirty) {
         var message = '...';
         modalThingy.open(message).then(callback || default);
     }

     function default() {
         $window.history.back();
     }
}

然而,这会吞噬使用 Promise 的力量(冷静)。

有没有办法返回一个 promise ,但如果没有任何东西链接到它,那么调用默认函数?

我正在使用 angularjs,但我想这个问题有一个通用的答案。

最佳答案

Is there a way of returning a promise, but if nothing is chained to it then call a default function?

当您从函数返回 Promise 时,调用者甚至还没有看到 Promise 对象,因此它甚至没有机会看到调用者在返回 Promise 后会做什么或不会做什么,所以什么也没有可以在返回 promise 之前提前设置或查看。

此外,标准 Promise 对象不提供任何查询附加或未附加处理程序的方法。


有一些黑客的事情可以做(尽管我不认为我会推荐它们)。

例如,您可以在返回的 Promise 上重写 .then() ,以便您能够查看在 Promise 解决之前它是否被调用,并且您可以跟踪该情况您所在州的信息。然后,当 Promise 确实得到解决时,如果尚未调用 .then(),您就可以执行默认行为。

以下是此类黑客计划的概述:

function someAsync() {
    var foundThenHandler = false;
    var p = new Promise(function(resolve, reject) {
        // some code that eventually and asynchronously
        // calls resolve or reject


        // as long as the code here executes some time in the future
        // after the caller has seen the returned promise and had a chance to 
        // add its own .then() handlers, then the code can check the
        // foundThenHandler variable to see if .then() was ever called on it

        // For example:
        setTimeout(function() {
            resolve();
            if (!foundThenHandler) {
               // carry out some default action
            }
        }, 1000);
    });
    var oldThen = p.then;
    p.then = function(resolveHandler, rejectHandler) {
        foundThenHandler = true;
        return oldThen.apply(p, arguments);
    }
    return p;
}


someAsync().then(function(val) {
    // async operation finished, default action will not be triggered
});

// no .then() handler attached, default action will be triggered
someAsync();

关于javascript - 如果没有其他函数链接到 promise ,则默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043102/

相关文章:

javascript - FullCalendar 独特的自定义每周 View

node.js - 使用 async_hooks 跟踪上下文

jQuery - 是否有办法中止 $.when 调用的 AJAX 调用列表?

node.js - 破坏 promise 链 - 停止执行下一个 'then'

javascript - 使用 vuejs 输入字段实时验证

javascript - HTML5 canvas 游戏将子弹射向鼠标点。

javascript - 将播放列表添加到 iframe 标记

javascript - AngularJS Controller 无限请求

javascript - 当我在 Angular/Javascript 中进行 api 调用时,如何在选项卡名称(标题)附近添加/激活加载微调器

jquery - AngularJS 和 jQuery : Splitting textarea into multiple textareas