I am having trouble getting a loop to return nested promises in the correct order. I am trying to recursively loop through a directory with subdirectories to get files and copy them to a new directory. This functionality is happening inside a Promise chain since other processes need to complete in order after the files are copied.
The following code works but when I console.log out a string after the .then()
it is logging before the promise has resolved.
The code is:
let newDirectory = /// helper function that returns promise of mkdirSync(exampleDir)
newDirectory.then(function(result){
getAllFiles('/TestDir').then((result) => {
console.log(result);
});
console.log('this should fire after the "result" from above');
//// rest of promises in promise chain
});
The recursive function I'm calling "getAllFiles" to go through "TestDir" and its sub folders and copy files to "ExampleDir"
const getAllFiles = function(dirPath, arrayOfFiles) {
return new Promise((resolve, reject) => {
var promises = [];
files = fs.readdirSync(dirPath)
arrayOfFiles = arrayOfFiles || []
files.forEach(function(file) {
if (fs.statSync(dirPath + "/" + file).isDirectory()) {
arrayOfFiles = resolve(getAllFiles(dirPath + "/" + file, arrayOfFiles));
} else {
promises.push(helper.copyFile(path.join(dirPath, "/", file),`/TestDir/${file}`))
}
}
})
Promise.all(promises).then(function(result){
resolve(result);
console.log('done with Promises');
}).catch((error) => {
reject(error);
});
}
The helper that copies the files returns a promise after the file has been copied
exports.copyFile = function(file, destDir){
return new Promise(function ( resolve, reject ){
fs.copyFile(file, destDir, (err) => {
if(err) reject( err );
else resolve('Successfully copied');
});
});
}
This actually seems to work but I am concerned it wont work with a large set of data since the
console.log('this should fire after the "result" from above');
fires before the other logs. The console looks like:
this should fire after the "result" from above
done with Promises /// how ever many files are copied
[ 'Successfully copied'] //// with a length of however many files are copied)
done with Promises //// this is fired once
Is this a log to be expected, or should all of the promises resolve and be logged before the "'this should fire after the "result" from above'" line is logged?