Wrap recursive files/dirs iteration with Promise <p>I need to check some directories tree for files and then create same directories structure on the server, and also create files list to upload to server. So I realise I need to wrap my dirs iterators with promise so I can get final file list on ".then()":</p> <pre><code>export function uploadHandler(filesAndDirs, currentDirectory) { return (dispatch, getState) =&gt; { filesToUpload = []; iterate(filesAndDirs, currentDirectory).then((whatResolved) =&gt; { console.log(whatResolved + ' is resolved'); // console.log(filesToUpload); }); } } </code></pre> <p>But I faced some trouble while resolving my promise, cause working with recursion I dont know exactly which file/dir is the last one:</p> <pre><code>function iterate(filesAndDirs, currentDirectory) { return new Promise(function(resolve) { for (let i = 0; i &lt; filesAndDirs.length; i++) { if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') { let dir = filesAndDirs[i]; createDirectory(dir.name, currentDirectory._id).then((directory) =&gt; { dir.getFilesAndDirectories().then((subFilesAndDirs) =&gt; { iterate(subFilesAndDirs, directory).then(() =&gt; { if (i + 1 == filesAndDirs.length) resolve('+++ by dir'); }); }); }); } else { filesToUpload.push({ file: filesAndDirs[i], directory: currentDirectory }); // If last item is file then I need to resolve the main promise // but same time if I will resolve promise here then // whole chain will break couse subdirectories handling async } }; }); } </code></pre> <p>I made it works for [dir] input but I cant handle it if [dir, file] input. What can I do here? Maybe its just bad idea to use Promise here?</p>