0

I have a function which reads dir(folders and files) and create MongoDB documents in one collection named Item. Each files located in nested folders will also be inserted inside of the MongoDB document.

My file function is like :

async generateFileItemInPath(path, itemName){
    let itemObj = new Item();
    //let itemObj = {};

    itemObj.itemName = itemName;
    itemObj.isAFile = true;
    itemObj.itemPath = path;

    itemObj.save(function (err) {
        if (err){
            console.log("Error");
        } else {
            console.log("No Error !");
            return itemObj;
        }
    });
} 

My folder function is like :

async generateFolderItemInPath(path, itemName){
    let itemObj = new Item();
    //let itemObj = {};

    itemObj.itemName = itemName;
    itemObj.isAFile = false;
    itemObj.itemPath = path;

    itemObj.save(function (err) {
        if (err){
            console.log("Error");
        } else {
            console.log("No Error !");
            return itemObj;
        }
    });
} 

And I call these functions from this recursive function :

async createItemsData(parentPath, itemName) {
    let resultList = [];
    let itemsPath = parentPath+itemName;

    let itemsInPath = fs.readdirSync(itemsPath);

    for(let i=0; i<itemsInPath.length; i++){
        let isDirAFile = fs.lstatSync(itemsPath + itemsInPath[i]).isFile();
        let isDirAFolder = fs.lstatSync(itemsPath + itemsInPath[i]).isDirectory();

        if(isDirAFile){
            let tempItemObj = await self.generateFileItemInPath(itemsPath, itemsInPath[i]);
            resultList.push(tempItemObj);
        } else if(isDirAFolder){
            let tempItemObj = await self.generateFolderItemInPath(itemsPath, itemsInPath[i]);
            tempItemObj.itemChildren = [];
            tempItemObj.itemChildren.push(await self.createItemsData(itemsPath, itemsInPath[i] + "\\"));
            resultList.push(tempItemObj);
        }
    }
    return resultList;
} 

My problem is whenever generateFileItemInPath, generateFolderItemInPath and createItemsData are called, code never waits for the result of these functions in createItemsData.

Some other solutions exists but they didnt help me. Thank you for your contributions.

evrnzz
  • 1
  • You won't be able to use await within traditional loop. see this question for info https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – laxman Jan 22 '20 at 10:27

1 Answers1

0

async / await works with promises only. So your two async functions need to return promises, or at least thenables (i.e. something with a .then() method). Currently, they aren't returning anything (and thus implicitly return undefined).

It looks like you're using Mongoose, right? The latest versions of Mongoose will return thenables from queries if you don't specify a callback, so you can just, for instance, return itemObj.save().

IceMetalPunk
  • 5,476
  • 3
  • 19
  • 26