使用javascript异步直到停止执行库

时间:2015-10-12 01:40:13

标签: javascript node.js

我使用的库我没有写过,无法修改以执行以下操作:

libx.on('something', function(x){
  liby.next_var(function(y,z){
    dance(x,y,z);
  })
})

不幸的是,我不想整夜跳舞。我希望能够在用户点击按钮时停止舞蹈的执行。

我尝试使用异步库直到功能:

var async = require('async');
var dancing = true;

async.until(function(){
  return !dancing;
},function(cb){
  libx.on('something', function(x){
    liby.next_var(function(y,z){
      dance(x,y,z);
    })
  })
},function(){
  console.log("dance() will no longer be called");
});

$('#stop').on('click', function(){
  // want to stop libx and liby calls
  dancing = false;
});

请记住,我无法修改libx的on方法的签名,或liby的next_var方法,如何控制和停止对这些方法的回调?

1 个答案:

答案 0 :(得分:0)

您对async.until的使用很好,问题是您正在注册一个事件处理程序,因此每次'something'发生时,您都会跳舞。 (听起来很有趣!)

在这种情况下,您甚至不需要使用async

libx.on('something', function (x) {
  liby.next_var(function (y, z) {
    dance(x, y, z);
  })
})

$('#stop').on('click', function () {
  libx.removeListener('something', function () {
    console.log("dance() will no longer be called");
  });
});

立即注册事件监听器,然后当您单击stop时,监听器将被移除,当'something'再次发生时您将不会跳舞。

好的,通过更好地理解手头的问题,你实际上非常接近解决方案。

var async = require('async');
var dancing = true;

function danceUntil (x, y, z) {
  async.until(function () {
    return !dancing;
  }, function (cb) {
    dance(x, y, z);
    cb();
  }, function () {
    console.log("dance() will no longer be called");
  });
}

libx.on('something', function (x) {
  liby.next_var(function (y, z) {
    danceUntil(x, y, z);
  })
})

$('#stop').on('click', function () {
  dancing = false;
});