Question

I am struggling to understand the scopes in javascript

I am making a simple call to google drive api and I want to access the variable outside the function.

My code;

var newDate;
getLiveDate(lastFileId);
console.log(newDate);

function getLiveDate(fileId) {
    var request = gapi.client.request({
        'path': 'drive/v2/files/' + fileId,
        'method': 'GET',
        'params': {
            'fileId': fileId
        }
    });

    request.execute(function(resp) {
        newDate = resp.modifiedDate;
    });
}

In the console, newDate is undefined why is this?

Was it helpful?

Solution

Those requests to google's API are async calls - so the next piece of code is executed while that function is still processing. The correct way to do this is to use callbacks rather than globals:

function getLiveDate(fileId, callback) {
    ...
    request.execute(function(resp) {
        callback(resp);
    });
}

And call this

getLiveDate(lastFileId, function(resp) {
    console.log(resp); //your data
});

OTHER TIPS

The API call is asynchronous. Your console.log() executes before a response has been received from the API.

The function passed to execute() is the callback and so you should move any logic that depends on the API response to there.

request.execute(function(resp) {
    newDate = resp.modifiedDate;

    // this is the callback, do your logic that processes the response here
});

Because, request.execute is an asynchronous function. Even before

newDate = resp.modifiedDate;

is executed,

console.log(newDate);

is executed. So, your best bet would be to print it in the callback function, like this

request.execute(function(resp) {
    newDate = resp.modifiedDate;
    console.log(newDate);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top