【问题标题】:AngularJS - can you chain then() to previously resolved promises?AngularJS - 你可以将 then() 链接到以前解决的承诺吗?
【发布时间】:2015-02-07 06:30:17
【问题描述】:

我看了这个帖子:Can you resolve an angularjs promise before you return it?

我正在尝试将它应用到我的代码中,但它似乎不起作用。

这是我的代码:

 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 应该可以正常工作...除非它与已解决的 Promise 有问题?

【问题讨论】:

  • $timeout 不支持 .flush。检查您的控制台日志是否有错误。 ngMock 支持它 - 你正在使用它吗?
  • 是的,它适用于我的所有测试
  • 看起来没有:plnkr.co/edit/sD4uCNrdMhh0Q8hQwLWp?p=preview(检查控制台)
  • 您使用的是哪个版本的 Angular?在添加 .then 后尝试添加 $rootScope.$digest()。请注意,在常规的非单元测试代码中它可以正常工作
  • 1.3.为什么要消化做任何事情?第一次刷新应该解决了承诺 - 然后第一次刷新按预期工作,因为它确实被触发了

标签: javascript angularjs promise


【解决方案1】:

问题在于 $timeout.flush() 方法,它仅在测试中可用(参见文档):https://docs.angularjs.org/api/ng/service/$timeout 和https://docs.angularjs.org/api/ngMock/service/$timeout

如果您删除它 - 一切都会按预期进行。

【讨论】:

  • 我在测试中检查这个,所以它应该在测试中工作,不是吗?
  • 你有没有在 angular.js 之后将 angular-mocks.js 添加到你的 html 中?
  • 是的,我们的 yeoman 脚手架管理着这个。请注意,当我调用flush时,第一个然后被触发,但是我之后添加的第二个没有被调用(我假设flush解决了超时承诺)
  • 好的,我不知道那里出了什么问题,但我认为这与承诺无关,因为应该可以在已解决的承诺上调用 then 并且代码将被执行:@ 987654323@
  • 我认为这与 ngMock $timeout 实现有关,我现在无法真正调试。
【解决方案2】:

正如@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.

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-31
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 2017-12-31
    • 1970-01-01
    相关资源
    最近更新 更多