Javascript 加入“;然后";方法在预定义的“";最后";方法 用例

Javascript 加入“;然后";方法在预定义的“";最后";方法 用例,javascript,angularjs,promise,angular-promise,Javascript,Angularjs,Promise,Angular Promise,我有一个$resource调用,它先执行,然后执行,最后执行清理。在等待服务器时,用户可能会与系统进行交互,我想在最终方法之前添加更多然后方法 如何将然后方法添加到在预定义的最后之前执行的现有$promise链中? 示例代码 下面是所需用例的简化代码示例。将then方法添加到现有链中可能会由$on、$watch或某些例程触发 function ctrl($scope, $timeout) { var a = $timeout(function() { console.lo

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

如何将
然后
方法添加到在预定义的
最后
之前执行的现有
$promise
链中?

示例代码 下面是所需用例的简化代码示例。将
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!
演示

您需要从一开始就在链中具有潜在的
调用。不过,你可以无限期地从他们的回访中回报新的承诺

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.