在预定义的“finally”方法之前将“then”方法添加到$ promise链中

时间:2014-07-09 14:24:31

标签: javascript angularjs promise angular-promise

使用案例

我进行了$resource调用,执行then后跟finally进行清理。在等待服务器时,用户可以与系统进行交互,我想在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

1 个答案:

答案 0 :(得分: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.