Error calling variable outside function

Asked

Viewed 37 times

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 filesis not empty, I have tried several ways to pass its value, or use a return, however rtn continues as null, I also tried to:

    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 by giving a console.log(rtn) outside the function, there is rtn.file with the supposed value, but when I call directly the same with rtn.file, says it’s undefined, what is happening and how I can solve the problem?

  • of the one console.log(response) inside the function to see

1 answer

0

Since the function is asynchronous, the.log(rtn) console is running before receiving the value. I suggest the following amendment:

    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);
    });
  • as it declared the variable outside the function o console.log(rtn) that was outside should work

  • As he reported, it works, but returns null, which was the value assigned before the function.

  • I need to call this data off function, any suggestions?

  • There may be a better option, but one possibility would be to use setTimeout(Function(){ console.log(rtn); }, 1000);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.