'Unable to return an array from a function in Google Apps Script

I am using the following function that lists all the folders I got in my Account.

function processGoogleDriveFolders() {
    var arrayAllFolderNames,continuationToken,folders,foldersFromToken,thisFolder;
    arrayAllFolderNames = [];

    folders = DriveApp.getFolders();
    continuationToken = folders.getContinuationToken();
    Utilities.sleep(18000);

    foldersFromToken = DriveApp.continueFolderIterator(continuationToken);
    folders = null;
    while (foldersFromToken.hasNext()) {
          thisFolder = foldersFromToken.next();
          arrayAllFolderNames.push(thisFolder.getName());
    };
    //  return arrayAllFolderNames;
    Logger.log(arrayAllFolderNames);

};    

But trying to return all that information as a return statement to place it in the Memory will make the function to not export annything so swapping the last two lines commeting one of each

return arrayAllFolderNames;
// Logger.log(arrayAllFolderNames);

Will not return anything



Solution 1:[1]

When I tried your script it returned all the folders I have access to, including the ones shared with me and that makes the list rather long... Btw, I think there is no need to add a sleep() in this function. I suggest the code below to get only the 'My Drive' folders by using DriveApp.getRootFolder().getFolders() instead of DriveApp.getFolders()

My test code goes like this :

function processGoogleDriveFolders() {
  var arrayAllFolderNames,folders,folder;
  arrayAllFolderNames = [];
    folders = DriveApp.getRootFolder().getFolders();
    while (folders.hasNext()) {
      folder = folders.next();
        arrayAllFolderNames.push(folder.getName());
    };
    //  return arrayAllFolderNames;
    Logger.log(JSON.stringify(arrayAllFolderNames));
}; 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Serge insas