0
我不明白为什么我的代码只适用于调试模式。我的变量musiques
我function createMusicBox()
处于调试模式和空物体在没有调试运行JavaScript&谷歌api:阵列工作只调试模式
var musiques = [];
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var auth = new googleAuth();
var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Lists the names and IDs of up to 10 files.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
var service = google.drive('v3');
service.files.list({
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
} else {
musiques=files;
console.log('Files:');
for (var i = 0; i < files.length; i++) {
musiques[i] = files[i];
var file = files[i];
console.log('%s (%s)', file.name, file.id);
}
}
});
}
// this function pulls music in my google drive
function createMusicBox() {
// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
return;
}
// Authorize a client with the loaded credentials, then call the Drive API.
authorize(JSON.parse(content), listFiles);
});
console.log(musiques);
}
我不知道Node.js,但从文档'fs.readFile'是一个异步函数,可能在调试模式'musiques'有时间在异步函数中进行评估:[doc here ...](https://nodejs.org /api/fs.html#fs_fs_readfile_path_options_callback) – Baro
你是对的,js脚本在异步函数结束之前执行自己。 问题是我不知道如何做,以订购js函数等待异步函数结束 –
有一个'fs.readFile'的同步版本'fs.readFileSync' [Doc](https:// nodejs .org/api/fs.html#fs_fs_readfilesync_path_options) –