$ q解析函数不会触发

时间:2015-02-20 15:14:28

标签: javascript unit-testing angular-promise

我以为我正确使用了AngularJS $q界面。但是我传递给then回调的函数永远不会被执行。我在resolve包裹的函数中调用$q。我已经确认正在调用resolve(),但似乎这与.then()链接的函数不同:

$q(function(resolve, reject) {
  resolve();
  reject();
  console.log("This happens");  //This shows that resolve() is being called
}).then(function() {
  console.log("This doesn't");  //Yet this never gets executed
}).catch(function() {
  console.log("This also doesn't happen");
});

输出结果为:

This happens

我做错了什么?

我的环境是使用mocha和sinon-chai进行的KarmaJS单元测试。

1 个答案:

答案 0 :(得分:1)

您需要致电$rootScope.$apply()

$q(function(resolve, reject) {
  resolve();
  console.log("This happens");  //This shows that resolve() is being called
}).then(function() {
  console.log("This too!");
});
$rootScope.$apply();