最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何递归地调用返回promise的函数?

运维笔记admin10浏览0评论

如何递归地调用返回promise的函数?

如何递归地调用返回promise的函数?

我想提取所有查询node-js服务的子文件夹和子Docs,每次调用该服务都会返回此类项的数组。我不知道文件夹树的深度,所以我想递归地调用一个函数,该函数最后将返回一个包含所有子文件夹和子文档的数组,该数组从根文件夹列表开始。每个文件夹都由一个文件夹ID标识。

所以我做了一个“ recPromise(fId)”,它返回了一个承诺。在内部,该函数递归调用recFun(folderId)。我开始从rootFolder调用“ recPromise(fId)”,因此一旦所有根目录都得到解决,我就可以继续。

rootFolders.map( folderOfRootlevel =>{
    var folderContentPromise = recPromise(folderOfRootlevel.id);
    folderContentPromises.push(folderContentPromise);
})

$q.all(folderContentPromises)
   .then(function(folderContent) { 
      // Do stuff with results.
}

function recPromise(fId){
    return new Promise((resolve, reject) => {
    var items = [];
    function recFun( folderId) {   // asynchronous recursive function
        function handleFolderContent( asyncResult) {  // process async result and decide what to do
        items.push(asyncResult);
        //Now I am in a leaf-node, no child-Folders exist so I return
        if (asyncResult.data.childFolders.length === 0){
              return items;
        }
         else {   
            //child_folders exist. So call again recFun() for every child-Folder     
            for(var item of asyncResult.data.childFolders)  {
               return  recFun(item._id); 
             }                              
        }
    }
    // This is the service that returns the array of child-Folders and child-Docs
    return NodeJSService.ListFolders(folderId).then(handleFolderContent);
   }
  resolve(recFun(fId));
 })
}


It works almost as expected except the loop inside else, where I call again recFun(). 
The NodeJSService will return an array of sub-Folders so I wish to call recfun() for every sub-Folder.
Now, I only get the result of the 1st sub-Folder of the loop, 
which makes sense since I have a return statement there. 
If I remove the return statement and call like this "recFun(item._id);" 
then it breaks the $q.all().
回答如下:

最后,我决定删除Promise包装函数,并使用async-await。

        var items = [];
        (async() => {
            for(var item of rootFolders)  {
                await recFun(item.id)
            }
            // Do stuff with items
           // go on form here..
        })()

        function listFolders(folderId) { 
            return new Promise( function( resolve, reject) {
                resolve(FolderService.ListFolders(folderId));  
            })
        }

        async function recFun(folderId) {
            var foldersResponse= await listFolders(folderId);
            items.push(foldersResponse);
            if (foldersResponse.data.childFolders.length === 0){
                return items ;
            }
            else {        
                for(var item of foldersResponse.data.childFolders)  {
                    await recFun(item._id); 
                }    
            }

        }
发布评论

评论列表(0)

  1. 暂无评论