我如何在 javascript 中使用长回调?
How can i use long callback in javascript?
我想做一个爬虫程序。这是 chrome 扩展名。
在我的程序中,一个功能是访问多个网页。这是我的计划。
访问页面,加载页面,抓取,访问下一页....
我希望我的程序是连续的。但是,'load page' 是异步的。因此,较低的代码不起作用。
function load_and_download(checked_list) {
for(var item of checked_list){
visit_page(item); //async function
crawl_page(item);
}
}
我找到了这样的解决方案。
function load_and_download(checked_list, now_index) {
visit_page(checked_list[now_index], function () {//load finish
crawl_page(checked_list[now_index]);
if (checked_list.length > now_index + 1)
load_and_download(checked_list, now_index+1);
})
}
上面的代码对我有用。但是,它是递归函数。
如果 checked_list 非常非常长,上面的代码是安全的吗?我知道递归代码有堆栈问题。 javascript 安全吗?
这里不是递归函数,如果visit_page
异步回调。我想将此模式称为 pseudorecursion,因为异步回调,每次对 load_and_download
的调用都将在单独的任务中发生,因此在调用堆栈中只会对该函数进行一次调用(每个任务)。一旦在 visit_page
中安排了异步操作,调用堆栈将再次展开并处理下一个任务。因此,虽然看起来是递归,但实际上并没有递归。
这是一个说明这一点的简化示例:
function asynchronous(callback) {
// Here an asynchronous action gets started and processed somewhere
setTimeout(callback, 1000);
// Execution continues synchronously and the callstack unwinds from here on
}
function pseudoRecursive() {
asynchronous(function () {
console.log("As we're in a new task, the callstack is basically empty:\n", (new Error()).stack);
pseudoRecursive();
});
// Here the callstack unwinds again
}
pseudoRecursive();
我想做一个爬虫程序。这是 chrome 扩展名。
在我的程序中,一个功能是访问多个网页。这是我的计划。
访问页面,加载页面,抓取,访问下一页....
我希望我的程序是连续的。但是,'load page' 是异步的。因此,较低的代码不起作用。
function load_and_download(checked_list) {
for(var item of checked_list){
visit_page(item); //async function
crawl_page(item);
}
}
我找到了这样的解决方案。
function load_and_download(checked_list, now_index) {
visit_page(checked_list[now_index], function () {//load finish
crawl_page(checked_list[now_index]);
if (checked_list.length > now_index + 1)
load_and_download(checked_list, now_index+1);
})
}
上面的代码对我有用。但是,它是递归函数。 如果 checked_list 非常非常长,上面的代码是安全的吗?我知道递归代码有堆栈问题。 javascript 安全吗?
这里不是递归函数,如果visit_page
异步回调。我想将此模式称为 pseudorecursion,因为异步回调,每次对 load_and_download
的调用都将在单独的任务中发生,因此在调用堆栈中只会对该函数进行一次调用(每个任务)。一旦在 visit_page
中安排了异步操作,调用堆栈将再次展开并处理下一个任务。因此,虽然看起来是递归,但实际上并没有递归。
这是一个说明这一点的简化示例:
function asynchronous(callback) {
// Here an asynchronous action gets started and processed somewhere
setTimeout(callback, 1000);
// Execution continues synchronously and the callstack unwinds from here on
}
function pseudoRecursive() {
asynchronous(function () {
console.log("As we're in a new task, the callstack is basically empty:\n", (new Error()).stack);
pseudoRecursive();
});
// Here the callstack unwinds again
}
pseudoRecursive();