Angular JS 中未调用 Promise 回调 [英] Promise callback not called in Angular JS
问题描述
如果我从 doStuff
调用 connect
,我会收到消息 套接字已连接",但是 回调
没有被调用.我在这里缺少什么?
If I call connect
from doStuff
, I get the message that "the socket is connected", but the callback
is not called. What am I missing here?
$scope.connect = function() {
var defer = $q.defer();
ws = new WebSocket("ws://server.com:port");
ws.onopen = function(){
console.log("Socket connected");
defer.resolve("socket connected");
};
return defer.promise;
}
$scope.doStuff = function() {
$scope.connect().then(function(data) {
console.log("And we're off!", data);
});
}
推荐答案
在 AngularJS 中,promise 结果在 $digest 循环内异步传播.因此,您使用 then() 注册的回调函数只会在进入 $digest 循环时被调用.
In AngularJS promise results are propagated asynchronously, inside a $digest cycle. So, your callback function registered with then() will only be called upon entering a $digest cycle.
因此,当您的套接字连接时,我们处于摘要循环中.then()
创建了一个新的 promise,但是 then()
的结果直到下一个摘要循环才会传播,这个循环永远不会出现(因为没有 $timeout
或 $http
或 DOM 事件来触发).正如@Ajay 刚刚发布的那样,如果您添加 $scope.$apply(),它将导致一个摘要循环,您将看到结果.
So, when your socket connects, we are in a digest cycle. then()
creates a new promise, but the results of that then()
will not be propagated until the next digest cycle, which never comes (because there is no $timeout
, or $http
, or DOM event to trigger one). As @Ajay just posted, if you add $scope.$apply(), it will cause a digest cycle and you'll see the results.
这篇关于Angular JS 中未调用 Promise 回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!