我查看了这篇文章: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应该正常工作...除非它已经解决了promises的问题?
答案 0 :(得分:0)
问题是$ timeout.flush()方法,它只在测试中可用(参见文档):https://docs.angularjs.org/api/ng/service/ $ timeout 和https://docs.angularjs.org/api/ngMock/service/ $ timeout
如果你删除它 - 一切都按预期工作。
答案 1 :(得分:0)
正如@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.
正如这里提到的那样,这段代码是正常运行的,它不需要摘要调用。只有在此代码从测试运行时才需要摘要。