Javascript $q.then不';调用回调
Javascript $q.then不';调用回调,javascript,angularjs,jasmine,Javascript,Angularjs,Jasmine,then回调不被调用的承诺的可能原因是什么? 例如: function testPromise() { console.log("this gets logged") return $q(function(resolve, reject) { console.log("this too") resolve("test") console.log("and this"); $rootScope.$apply() console.log("and th
then
回调不被调用的承诺的可能原因是什么?
例如:
function testPromise() {
console.log("this gets logged")
return $q(function(resolve, reject) {
console.log("this too")
resolve("test")
console.log("and this");
$rootScope.$apply()
console.log("and this too");
})
}
testPromise().then(function(result){
console.log("this never gets logged")
});
难道我没有看到什么明显的东西吗?谢谢。这取决于您使用的AngularJS版本 在AngularJS 1.2中,它要求您创建一个称为“延迟”的东西,并单独返回一个承诺
但是,如果是这种情况,您应该会在控制台中收到一个错误,告诉您是这样的。这完全取决于您从哪里调用
$rootScope.$apply()
。如果它在摘要周期的执行期间,那么您的调用将导致错误并停止脚本的执行
您的示例在没有$rootScope.$apply()
的情况下运行良好。你能提供更多关于你打算如何使用它的上下文吗?我希望这能有所帮助。
我想这就是你使用$q的方式。
所以我做了一个有效的例子
在我的示例中,我在服务中使用$q,并使用$timeout延迟其响应
我删除了$apply(),我不知道你为什么要用它
app.factory('TestingService', TestingService);
function TestingService($q, $timeout) {
return {runPromise:runPromise};
function runPromise() {
return $q(function(resolve, reject) {
console.log("inside my $q")
$timeout(function(){
resolve("$q is working fine");
}, 2000); //Lets use $timeout, just to see the result
});
};
}
然后
TestingService.runPromise().then(
function(result){
console.log('result::',result);
vm.test = result;
});
希望能有帮助。谢谢大家的回答。正如你们中的一些人所提到的,它与我从哪里调用这个函数有关。因此,从常规函数调用是有效的。从另一个
的回调调用,然后从上下文.sync()调用,然后从上下文.sync().then()
调用,其中上下文.sync()
是一个单词外接程序
的承诺(谁知道它实际上是什么)-没有。因此,我最终将我的函数转换为接受回调,而不是承诺。类似的问题以前也被问过很多次,不过我认为您的具体问题来自于在return语句中调用$rootScope.$apply()
,而不是在它之前调用,需要额外的摘要。请尝试在$rootScope.$digest()
之前添加$rootScope.$apply()
。非常确定$q
会自动在解析/拒绝时触发范围摘要。您不需要手动添加它。我同意Phil的观点,实际上由于某种原因,在我的示例中调用$apply()时遇到问题。您使用的是Angular的哪个版本?