如何在角度中使用$ state.go()时停止一个promise链?

时间:2014-12-06 19:02:56

标签: angularjs angular-ui-router

我有一系列承诺,负责初始化我的控制器。在此链中,如果不满足某个条件,最好通过$state.go()将用户发送到另一个状态,并停止运行承诺链的其余部分。如何实现这一目标?

loadData1() .then(function(){ return loadData2(); }) .then(function(){ if (...) { $state.go(...); // how should the existing promise chain be killed off or stopped? } else { return loadData3(); } }) .then(function(){ return loadData4(); }) .then(function(){ console.log('controller initialized successfully'); }, function(error){ console.log('failed to initialize controller'); });

1 个答案:

答案 0 :(得分:1)

而不是立即调用$state.go,抛出错误并在最后的错误处理程序中检查它。

loadData1()
.then(function () {
  return loadData2();
})
.then(function () {
  if (exceptionalCondition) {
    throw new Error('[MyCtrl:loadData2] Data failed to load!');
  }
  return loadData3();
})
...
.then(function () {
  console.log('controller initialized successfully');
},
function (error) {
  if (/^\[MyCtrl:loadData2\]/.test(error.message)) {
    $state.go(redirect);
  } else {
    console.log('failed to initialize controller');
  }
});

使用promises的好处是它们会处理错误并立即终止链接。

相关问题