I'm trying to write a function which reads a particular column from a Google Sheet and pushes all of those values into an array which I can use later.
I simply used the Node.js sample from Google and modified it to suit my needs. It works (almost) except I'm unsure how to properly return the array populated with the data from the sheet.
There seems to be a sort of timing issue where it returns the empty array first and then populates it after. I'm not sure how to go about making it wait until the values are pushed before returning the array.
I have omitted the authentication methods as they are not relevant to the issue I am having.
// Function to get values from sheet (to check for duplicate submissions)
function getSubmissions(sheet, period) {
let data = []; // Array to capture response from sheets.get
/*
Function to read through column A1 and push all cells into an array for me to later
check against for duplicates.
*/
function readSubmissions(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: sheet,
range: period + '!A3:A',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
for(let i = 0; i<rows.length; i++) {
console.log(rows[i]); // Correctly prints all cells A3:A AFTER it returns the empty array
data.push(rows[i]);
}
console.log(data); // Correctly prints data array again after it returns the empty array
} else {
console.log('No data found.');
}
});
}
return data; // Returns empty array; executing before the loop pushes rows[i] to data[].
};