繁体   English   中英

AngularJS-您可以将then()链接到先前解决的Promise吗?

[英]AngularJS - can you chain then() to previously resolved promises?

我看了这篇文章: 在返回之前,您可以解决angularjs承诺吗?

我正在尝试将其应用于我的代码,但似乎无法正常工作。

这是我的代码:

 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 () { ... }); 

注意:这段代码在业力测试函数中运行,因此$ timeout应该正常工作...除非它的承诺有问题?

问题是$ timeout.flush()方法,该方法仅在测试中可用(请参阅文档): https : //docs.angularjs.org/api/ng/service/ $ timeout和https://docs.angularjs.org/ api / ngMock / service / $ 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.

正如这里的人所提到的,如果此代码能够正常运行,则不需要摘要调用。 仅由于此代码正在测试中运行,因此才需要摘要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM