gpt4 book ai didi

javascript - 全局变量未定义

转载 作者:行者123 更新时间:2023-11-28 19:54:32 27 4
gpt4 key购买 nike

我正在努力理解 javascript 中的范围

我正在对 Google Drive 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未定义,这是为什么?

最佳答案

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

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

并称之为

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

关于javascript - 全局变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22815473/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com