javascript - 将 "then"方法添加到 $promise 链中预定义的 "finally"方法之前

标签 javascript angularjs promise angular-promise

用例

我有一个 $resource 调用,它执行 then ,然后执行 finally 进行清理。在等待服务器时,用户可能会与系统交互,我想在 finally 方法之前添加更多 then 方法。

如何将 then 方法添加到现有 $promise 链中,并在预定义的 finally 之前执行?

示例代码

下面是所需用例的简化代码示例。将 then 方法添加到现有链可以由 $on$watch 或某些例程触发。

function ctrl($scope, $timeout) {
    var a = $timeout(function() {
        console.log("Time out complete");
        return this;
    }, 1000).finally(function() {
        console.log("Finally called!");
    });

    // some logic

    // some events

    // some stuff happens

    // then something might insert this 
    // into the promise chain.
    a.then(function() {
        console.log("Another then!");
    });
};

结果

期望的结果:

> Time out complete
> Another then!
> Finally called!

当前结果:

> Time out complete
> Finally called!
> Another then!

演示

jsFiddle

最佳答案

您需要从一开始就在链中包含潜在的 then 调用。不过,您可以从回调函数中无限地返回新的 Promise。

var todo = [];
function checkTodos() {
    if (todo.length)
        return todo.shift()().then(checkTodos);
        // do the chained task, and when finished come back to check for others
    else
        return todo = null;
}
function add(task) {
    if (todo)
        todo.push(task);
    else
        throw new Error("Sorry, timed out. The process is already finished");
}

$timeout(function() {
    console.log("Time out complete");
    return this;
}, 1000).then(checkTodos).finally(function() {
    console.log("Finally called!");
});

// some stuff happens
// then something might insert this into the promise chain:
add(function() {
    console.log("Another then!");
});
// Assuming it was fast enough.

关于javascript - 将 "then"方法添加到 $promise 链中预定义的 "finally"方法之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24656352/

相关文章:

angularjs - 如何在 $http.get 请求中传递日期

javascript - 使用 Promise 更好地处理 AJAX 嵌套?

javascript - 即使有 When Promise 回调金字塔

javascript - 如何在 Angular ng-repeat中使用累积和

javascript - AngularJS 等待 $http 请求

javascript - 选择 map 控件外部的 Google map 多边形并修改属性

javascript - 为什么这个 Canvas 动画在使用 ngRoute 第二次加载时挂起?

node.js - 链接 promise

javascript - angularjs - 我如何获得内容长度标题

javascript 如何找到包含文本的 DOM 节点?