0

用例

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

如何将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

4

1 回答 1

1

您需要then从一开始就在链中进行潜在调用。不过,您可以从他们的回调中无限返回新的承诺。

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.
于 2014-07-09T14:32:30.030 回答