0

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()":

export function uploadHandler(filesAndDirs, currentDirectory) {
  return (dispatch, getState) => {
    filesToUpload = [];
    iterate(filesAndDirs, currentDirectory).then((whatResolved) => {
      console.log(whatResolved + ' is resolved');
      // console.log(filesToUpload);
    });  
  }
}

But I faced some trouble while resolving my promise, cause working with recursion I dont know exactly which file/dir is the last one:

function iterate(filesAndDirs, currentDirectory) {
  return new Promise(function(resolve) {
    for (let i = 0; i < filesAndDirs.length; i++) {
      if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') {
        let dir = filesAndDirs[i];
        createDirectory(dir.name, currentDirectory._id).then((directory) => {
          dir.getFilesAndDirectories().then((subFilesAndDirs) => {
            iterate(subFilesAndDirs, directory).then(() => {
              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
      }
    };
  });
}

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?

user1341315
  • 115
  • 1
  • 8

0 Answers0