我已经编写了一个API服务,它创建了一个特殊的函数next
,它使用下一页数据调用自身。它允许我做类似的事情:
let req = getSomeData({ param: true }, function(err, res) {
// Do something
if (res.next) {
res.next();
} else {
// All data processed
}
})
如果我想提前停止这种自动分页,我假设我可以设置req = null
,它会阻止它再次运行,但是回调函数会继续运行。
简约示例如下:
var parent = function() {
var runner = function(func) {
var next = function() {
return runner(func);
}
func(next)
}
var handler = function(next) {
console.log('handler called')
setTimeout(next, 2000);
}
runner(handler);
}
var child = new parent();
setTimeout(function() {
console.log('killing child');
child = undefined;
console.log('child is ' + typeof child);
}, 5000)
即使在5秒child = undefined
之后,处理程序功能仍然每两秒钟调用一次。
答案 0 :(得分:0)
添加stop
功能使其更明智:
var parent = function() {
var keepRunning = true;
var runner = function(func) {
var next = function() {
return runner(func);
}
if(keepRunning)
func(next)
}
var handler = function(next) {
console.log('handler called')
setTimeout(next, 2000);
}
this.stop = function(){
keepRunning = false
}
runner(handler);
}
var child = new parent();
setTimeout(function() {
console.log('killing child');
child.stop()
console.log('child is ' + typeof child);
}, 5000)