我进行了$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!
答案 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.