Error calling variable out of function

0

I have the following code:

    var rtn = null;
    gapi.client.drive.files.list({
        q: "mimeType = 'application/vnd.google-apps.folder'",
    }).then(function(response) {
        var files = response.result.files;
        rtn = files[0]["id"];
    });
    console.log(rtn);

The variable files is not empty, I have already tried in several ways to pass its value, or use return , but rtn is still as null , I also tried:

    var rtn = {};
    gapi.client.drive.files.list({
        q: "mimeType = 'application/vnd.google-apps.folder' and name = '"+name+"' and '1zo-0IG0d7v91P25Ln6haxF2isMbt0hN8' in parents",
    }).then(function(response) {
        var files = response.result.files;
        rtn.file = files[0]["id"];
    });

And when I give a console.log(rtn) out of the function, there is rtn.file with the supposed value, but when I directly call it with rtn.file , it says undefined , what is happening and how can I solve it? problem?

    
asked by anonymous 06.05.2018 / 13:07

1 answer

0

Because the function is asynchronous, console.log (rtn) is running before it receives the value. I suggest the following change:

    var rtn = null;
    gapi.client.drive.files.list({
        q: "mimeType = 'application/vnd.google-apps.folder'",
    }).then(function(response) {
        var files = response.result.files;
        rtn = files[0]["id"];
        console.log(rtn);
    });
    
06.05.2018 / 15:11