无极回调角JS不叫 [英] Promise callback not called in Angular JS

查看:127
本文介绍了无极回调角JS不叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我把从doStuff连接,我得到了套接字连接到的消息,但回调不叫。我缺少的是在这里吗?

  $ scope.connect =功能(){
    变种延迟= $ q.defer();
    WS =新的WebSocket(WS://server.com:端口);
    ws.onopen =功能(){
        的console.log(套接字连接);
        defer.resolve(插座连接);
    };
    返回defer.promise;
}$ scope.doStuff =功能(){
    $ scope.connect()。然后(功能(数据){
        的console.log(我们出发了!,数据);
    });
}


解决方案

在AngularJS保证最终的结果是异步传播,一个$消化周期内。所以,你的回调函数,然后注册()只将在进入$消化周期被调用。

所以,当你的插座连接,我们正处在一个周期的消化。 则()创建一个新的承诺,但该结果则()将不会传播,直到下一次摘要循环,这还没有出现(因为没有 $超时 $ HTTP ,或DOM事件来触发一个) 。由于@Ajay刚刚发布,如果添加$范围。$适用(),就会造成消化周期,你会看到的结果。

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);
    });
}

解决方案

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.

这篇关于无极回调角JS不叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆