Promise callback not called in Angular JS

后端 未结 2 708
后悔当初
后悔当初 2020-12-16 02:34

If I call connect from doStuff, I get the message that \"the socket is connected\", but the callback is not called. What am I

相关标签:
2条回答
  • 2020-12-16 02:47

    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.

    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.

    0 讨论(0)
  • 2020-12-16 03:05

    You should be using $scope.$apply() please find the below working code

    function formctrl($scope,$q,$timeout) {
                $scope.connect = function () {
                    var defer = $q.defer();
                    var ws = new WebSocket("ws://echo.websocket.org");
                    ws.onopen = function (evt) {
                        defer.resolve("socket connected");
                        $scope.$apply();
                    }
                    return defer.promise;
                }
    
                $scope.raise = function () {
                    $scope.connect().then(function (data) {
                        alert(data);
    
                    });
                }
    
    
            }
    
    0 讨论(0)
提交回复
热议问题