繁体   English   中英

全局变量未定义

[英]Global variable undefined

我正在努力了解javascript的范围

我正在对Google驱动器api进行简单调用,我想在函数外部访问变量。

我的代码;

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

在控制台中,newDate是未定义的,为什么呢?

API调用是异步的。 您的console.log()在从API收到响应之前执行。

传递给execute()的函数是回调,因此您应该将依赖于API响应的任何逻辑移到那里。

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

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

因为request.execute是一个异步函数。 甚至之前

newDate = resp.modifiedDate;

被执行

console.log(newDate);

被执行。 因此,最好的选择是将其打印在回调函数中,如下所示

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

对Google API的那些请求是异步调用-因此在该函数仍在处理的同时执行下一段代码。 正确的方法是使用回调而不是全局变量:

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

并称之为

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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