Search code examples
jquerygoogle-apipromisegoogle-drive-apigoogle-api-javascript-client

Where does the 'response' come from in the JavaScript sample code for Google Drive API?


I studied this page (https://developers.google.com/drive/v3/web/quickstart/js) and found the code as follows:

/**
* Print files.
*/    
function listFiles() {
        gapi.client.drive.files.list({
            'pageSize': 10,
            'fields': "nextPageToken, files(id, name)"
        }).then(function(response) {
            appendPre('Files:');
            var returnedFiles = response.result.files;
            alert(returnedFiles);
            if (returnedFiles && returnedFiles.length > 0) {
                for (var i = 0; i < returnedFiles.length; i++) {
                    var file = returnedFiles[i];
                    alert(file);
                    appendPre(file.name + ' (' + file.id + ')');
                }
            } else {
                appendPre('No files found.');
            }
        });
    }

I wonder where does the "response" come from in the function code as following?

}).then(function(response) {

And if the "response" in following line are the same?

Line1:  }).then(function(response) {

Line2:  var returnedFiles = response.result.files;

Solution

  • gapi.client.drive.files.list(...) returns a Promise. See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise if you're new to Promises.

    The promise resolves (the then(f) bit) with a response object which in turn contains a result object which is defined at https://developers.google.com/drive/v3/reference/files/list