I\'m looking to execute a callback upon the full completion of a recursive function that can go on for an undetermined amount of time. I\'m struggling with async issues and was
Typically when you write a recursive function it will do something and then either call itself or return.
You need to define callback
in the scope of the recursive function (i.e. recurse
instead of start
), and you need to call it at the point where you would normally return.
So, a hypothetical example would look something like:
get_all_pages(callback, page) {
page = page || 1;
request.get({
url: "http://example.com/getPage.php",
data: { page_number: 1 },
success: function (data) {
if (data.is_last_page) {
// We are at the end so we call the callback
callback(page);
} else {
// We are not at the end so we recurse
get_all_pages(callback, page + 1);
}
}
}
}
function show_page_count(data) {
alert(data);
}
get_all_pages(show_page_count);