简体   繁体   English

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

[英]Use javascript async until to stop execution of library

I'm using libraries I didn't write and can't modify to do the following: 我正在使用没有写的库,无法修改以执行以下操作:

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

Unfortunately, I don't want to dance all night. 不幸的是,我不想整晚跳舞。 I want to make it possible to stop the execution of dance when a user clicks a button. 我想让用户单击按钮时停止执行跳舞。

I tried to do this with the async library's until function: 我试图用异步库的直到函数来做到这一点:

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

Keeping in mind I can't modify the signature of the on method for libx, or the next_var method of liby, how can I control and stop the callbacks to these methods from firing? 请记住,我无法修改libx的on方法或liby的next_var方法的签名,如何控制和阻止触发这些方法的回调?

Your usage of async.until is fine, the issue is that you're registering an event handler so every time 'something' happens, you're going to dance. 您对async.until用法很好,问题在于您正在注册一个事件处理程序,因此每次'something'发生时,您都会跳舞。 (Sounds fun!) (听起来很有趣!)

In this case, you don't even need to use async : 在这种情况下,您甚至不需要使用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");
  });
});

The event listener is registered immediately and then, when you click on stop , the listener is removed and you won't be dancing when 'something' happens again. 事件侦听器立即注册,然后,当您单击stop ,侦听器将被删除,并且再次发生'something'时您将不会跳舞。


Alright, with a better understanding of the problem at hand, you were actually really close to the solution. 好了,有了对当前问题的更好的了解,您实际上已经很接近解决方案了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM