Javascript AngularJS-您能将then()链接到以前解析的承诺吗?

Javascript AngularJS-您能将then()链接到以前解析的承诺吗?,javascript,angularjs,promise,Javascript,Angularjs,Promise,我看了这篇文章: 我试图将它应用到我的代码中,但它似乎不起作用 这是我的密码: var myPromise = $timeout(function () { ... }, 1000); myPromise.then(function () { ... }); // the code in here runs $timeout.flush(); // this causes the promise to become resolved and the code in the

我看了这篇文章:

我试图将它应用到我的代码中,但它似乎不起作用

这是我的密码:

 var myPromise = $timeout(function () { ... }, 1000);

    myPromise.then(function () { ... }); // the code in here runs

    $timeout.flush(); // this causes the promise to become resolved and the code in the 1st then above to run.

    // I expect this code to run immediately, since the promise is already resolved - but it doesn't
    myPromise.then(function () { ... }); 

注意:此代码在karma测试函数中运行,因此$timeout应该正常工作。。。除非它与已解决的承诺有问题?

问题是$timeout.flush()方法,它仅在测试中可用(请参阅文档):$timeout 和$timeout


如果您删除它,一切都会正常工作。

正如@Rytmis所指出的,调用$scope.digest是有效的。下面是代码:

var myPromise = $timeout(function () { ... }, 1000);

    myPromise.then(function () { ... }); // the code in here runs

    $timeout.flush(); // this causes the promise to become resolved and the code in the 1st then above to run.

    // I expect this code to run immediately, since the promise is already resolved - but it doesn't
    myPromise.then(function () { ... }); 

    rootScope.$digest(); // This will trigger the 2nd promise.

正如这里的人所提到的,如果这段代码正常运行,它就不需要摘要调用。只需要摘要,因为此代码是从测试运行的。

$timeout不支持.flush。检查控制台日志中的错误。ngMock支持它-这就是你正在使用的吗?是的,它在我的所有测试中都可以正常工作:(检查控制台)你在使用什么版本的Angular?尝试在
之后添加
$rootScope.$digest()
。然后添加
。请注意,在常规的非单元测试代码中,它只适用于1.3。消化为什么要做什么?第一次刷新应该解决了这个问题,并且刷新在第一次刷新中的效果与预期一样,因为它确实在测试中得到了triggeredIm的检查,所以它应该在测试中工作,不是吗?你有没有在angular.js之后将angular-mocks.js添加到你的html中?是的,我们的yeoman脚手架管理这一点。请注意,当我调用flush时,会触发第1个,但随后添加的第2个不会被调用(我假设flush解决了超时承诺)好的,我不知道那里出了什么问题,但我假设这与承诺无关,因为应该可以调用
,然后在解析的promise上执行
,代码将被执行:我假设这与ngMock$timeout实现有关,现在我无法真正调试它。