Chris Trevorrow Chris Trevorrow - 10 months ago 140
Node.js Question

How to pass back the array

I am trying to pass the array named 'sheetsArray' out of the code below so that I may utilize it for some tasks. I cannot for the life of me figure out how to do this, despite trying many things and googling for hours. I'm sure it's easy but I'm not even sure what I should be searching that I'm not.

var sheetsArrayOut = sheets.spreadsheets.get({
auth: googleauth,
spreadsheetId: outputDOCID,
}, function(err,response) {
if (err) {
console.log('ERROR:' + err);
return
}
var sheets = response.sheets;

if (sheets.length == 0) {
console.log('No data found.');
} else {
var sheetsArray = [];
for (i = 0; i < sheets.length; i++) {
sheetsArray.push(sheets[i].properties.title);
}
}
console.log(sheetsArray[4]); // this returns the sheet name
return sheetsArray;
});

console.log(sheetsArrayOut[4]); // this returns undefined

Answer Source

It returns undefined because I suspect the function is asynchronous. In this instance you can probably use a callback to good effect:

function getData(function (sheetsArray) {
  // do things with sheetsArray
});

function getData(callback) {
  sheets.spreadsheets.get({
    auth: googleauth,
    spreadsheetId: outputDOCID,
  }, function(err,response) {
    // do a bunch of things
    callback(sheetsArray);
  });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download