简体   繁体   中英

Global variable undefined

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?

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);
});

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM