-1

In the function below, the existingFiles object is returned empty.

If I print it at the end of the 'service.files.list' then I see the expected results.

What am I missing?

For sure there are older posts with the same/similar question but I possibly miss the correct keyword when searching for those.

function searchFiles(auth, fileName) {
    "use strict";

    let service = google.drive('v3');
    let existingFiles = new Object();

    service.files.list({
        auth: auth,
        q: "name contains '"+fileName+"' and trashed = false",
        spaces: 'drive',
        pageSize: 100,
        fields: "nextPageToken, files(id, name)"
    }, function(err, response) {
        if (err) {
            doNotify(hipchatChannelID, hipchatFromUser, 'The API returned an error: '+err,'red');
            return;
        }
        let files = response.files;
        if (files.length == 0) {
            //console.log('No files found.');
        } else {
            for (let i = 0; i < files.length; i++) {
                let file = files[i];
                existingFiles = { 'fileName':file.name, 'fileID':file.id };
            }
        }
    });

    //console.log(JSON.stringify(existingFiles));
    return existingFiles;
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
delt
  • 1
  • 1

2 Answers2

2

The call to the function service.files.list is asynchronous that's the reason empty object is returned

Try returning after the for loop

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163
0

Because existingFiles get a value only if(files.lenght!=0), in fact if files.lenght == 0 existingFiles will be null.