我使用的库不是我编写的,无法修改来执行以下操作:
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 方法的签名,我如何控制和停止触发这些方法的回调?
最佳答案
您对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");
});
});
事件监听器会立即注册,然后,当您单击停止
时,监听器将被删除,并且当'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;
});
关于javascript - 使用 javascript async Until 停止库的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072038/