0

I am trying to access files from google drive using javascript. I have successfully done this. Now I want to display the files on a popup. Please see code below, there must be something I am not aware of.

//this code successfully retrieve files, I am trying to put the results into an array to access them later. 
function listFiles(search, owner) {
    var file_results = new Array();
    gapi.client.drive.files.list({
        'pageSize': 10,
        'fields': "nextPageToken, files(id, name, webViewLink)",
        'q': "fullText contains '" + search + "' and trashed=false and '" + owner + "' in owners"
    }).then(function(response) {
        var files = response.result.files;
        if (files && files.length > 0) {
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                file_results.push(file);
            }
        } else {
            return false;
        }
    });
    return file_results;
}
//here I am trying to run the function and get the list of files
$("#search_files").click(function(e) {
    e.preventDefault();
    var owner = $(this).data('owner');
    var name = $(this).data('name');
    var files = parent.listFiles(name, owner);
    console.log(files);
    //this will log [ 0: {id: xxxxxx name: xxxxxxx webViewLink: xxxxxx }]
    //I would like to check first if there were any results of files 
    //i.e files.length will return 0 even if there were files found. 
    //I tried to access files.id is undefined. files[0] also undefined. 
});
joanb
  • 169
  • 1
  • 1
  • 17
  • 1
    `if` there are files, you push them onto an array, and then return an empty array. Why? Change: `return file_results = []` – Randy Casburn Jul 01 '19 at 15:08
  • You're missing that the call to `gapi.client.drive.files.list` is asynchronous and that you are trying to access the list before it's there (if it gets there at all). – Jared Smith Jul 01 '19 at 15:08
  • 1
    @RandyCasburn hard to tell because of the indentation issues, but looks like OP is actually trying to read the list in a click handler in a different scope. – Jared Smith Jul 01 '19 at 15:09
  • You are right - I missed this: `var files = parent.listFiles(name,owner);` – Randy Casburn Jul 01 '19 at 15:10
  • @Randy Casburn Thanks for the catch! I fixed that, but I am able to get the list of files. my confusion I guess is the result an array? an object? or something else. – joanb Jul 01 '19 at 15:18

0 Answers0