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

Default behavior if no other functions chained to a promise

本文关键字:默认 promise 其他 函数 链接 如果没有      更新时间:2023-09-26

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

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

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

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

是否有返回promise的方法,但如果没有任何链接,则调用默认函数

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

有没有一种方法可以回报承诺,但如果没有任何东西与之相连然后调用默认函数?

在您从函数返回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();