异步递归函数结束后的回调

use*_*est 17 javascript recursion asynchronous callback

下面的函数以递归方式在文件夹中打印Chrome书签.在处理完最终递归循环后,如何更改下面的函数来调用另一个函数?chrome.bookmarks.getChildren()是异步的,这使得很难知道函数何时完成处理所有内容.

谢谢.

    for (var i = 0; i < foldersArray.length; i++) {
        // The loop makes several calls with different folder IDs.
        printBookmarks(foldersArray[i]);  
    }

    // I'd like any code here to be run only after the above has 
    //finished processing    

    function printBookmarks(id) {
        chrome.bookmarks.getChildren(id, function(children) {
           children.forEach(function(bookmark) { 
               console.debug(bookmark.title);
               printBookmarks(bookmark.id);
           });
        });
    }
Run Code Online (Sandbox Code Playgroud)

编辑:对不起,我不认为我在初始代码示例中是清楚的.我已经更新了代码,通过多次调用函数来显示我对异步函数的问题.我想在printBookmarks函数调用之后的任何代码等待所有printBookmarks函数完成处理.

Eri*_*sen 27

你的异步方法实例可能都在同时执行,你不知道预先有多少.因此,您必须保持计数,然后在最后一个异步方法完成时使用回调.

for (var i = 0; i < foldersArray.length; i++) {
    // The loop makes several calls with different folder IDs.
    printBookmarks(foldersArray[i], thingsToDoAfter);
}

function thingsToDoAfter() {
    // I'd like any code here to be run only after the above has 
    // finished processing.
}

var count = 0;

function printBookmarks(id, callback) {
    count++;
    chrome.bookmarks.getChildren(id, function(children) {
        children.forEach(function(bookmark) { 
            console.debug(bookmark.title);
            printBookmarks(bookmark.id, callback);
        });
        count--;
        if (count === 0 && callback)
            callback();
    });
}
Run Code Online (Sandbox Code Playgroud)


dfb*_*dfb -1

可能是一个更好的方法来解决这个问题,但你可以添加一个深度参数,比如

printBookmarks('0', 0);

function printBookmarks(id, depth) {
    chrome.bookmarks.getChildren(id, function(children) {
        children.forEach(function(bookmark) { 
            console.debug(bookmark.title);
            printBookmarks(bookmark.id, depth + 1);
        });
        if(depth == 0) yourFunction();
    });     
}
Run Code Online (Sandbox Code Playgroud)

编辑回应评论

这是另一个答案的变体,其方法略有不同。

runCount = 0;
for (var i = 0; i < foldersArray.length; i++) {
    // The loop makes several calls with different folder IDs.
    printBookmarks(foldersArray[i]);  
    runCount++;
}

while(runCount > 0) { // sleep for 10ms or whatnot}
// I'd like any code here to be run only after the above has 
// finished processing.    

function printBookmarks(id) {
    chrome.bookmarks.getChildren(id, function(children) {
        children.forEach(function(bookmark) { 
            console.debug(bookmark.title);
            printBookmarks(bookmark.id);
            runCount--;
        });
    });
}
Run Code Online (Sandbox Code Playgroud)