Asynchronous Calls and Recursion with Node.js

后端 未结 6 718
[愿得一人]
[愿得一人] 2021-02-09 10:34

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

6条回答
  •  旧巷少年郎
    2021-02-09 11:14

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

提交回复
热议问题