等待角度在套接字连接后呈现元素

时间:2016-01-18 08:29:11

标签: javascript angularjs sockets socket.io render

我希望在成功的套接字connectangular呈现元素时触发函数。

Ex. <canvas id="{{currentUserId}}"></canvas>

我想在我的代码中关注:

socket.on('connect',function(){
  until(<above canvas is present>)
    callMe();
});

1 个答案:

答案 0 :(得分:0)

使用async库找到解决方案:

socket.on('connect',function(){
    async.until(
      function(){
        return $('#canvasId').length > 0;
      },
      async.ensureAsync(
        function(retry){
        console.log('trying');
        retry(null,null);
        }
      ),
      function(err,result){
        console.log('rendered');
        callMe();
      }
    );
  });

以下是解释:

async.until(test,async.ensureAsync(fn),callback){}

test : return true/false, if returns false fn will be called and this will repeat until true is returned and on that final callback is called

fn: do some action, for my case I just wanted to wait, so I am not performing any action

async.ensureAsync(fn) : ensures that one fn is called in one tick and prevents stack overflow if there are too many attempts

callback: is called when test returns true