I'm using google sheets with OAuth 2.0
I have a function where I call
await createSpreadsheetEntry(body, submittedValues, logger).then(
function (value) {
console.log(value);
},
function (error) {
console.log("error in promise: " + error);
}
);
My problem is that vaue is always empty when coming from this
async function createSpreadsheetEntry(body, submittedValues, logger) {
var value1 = "";
var value2 = "";
const doc = new GoogleSpreadsheet(process.env.SHEET_KEY);
try {
await doc.useServiceAccountAuth(creds, SCOPES);
console.log("Authenticated to Google");
} catch (error) {
logger.error("Error while authenticating: " + error);
}
const client = new google.auth.JWT(
creds.client_email,
null,
creds.private_key,
["https://www.googleapis.com/auth/spreadsheets"]
);
var sheetId = process.env.SHEET_KEY;
client.authorize(function (err, tokens) {
if (err) {
console.log("err: " + err);
return;
}
const gsapi = google.sheets({ version: "v4", auth: client });
const opt = { spreadsheetId: sheetId, range: "Sheets1!A1:J1" };
var request = {
spreadsheetId: sheetId,
range: "Sheet1!A1:B10",
auth: client,
};
sheets.spreadsheets.values.get(request , function (err, response) {
if (err) {
console.log("err: " + err);
return;
}
var vArray = response.data.values.find((document) => {
return document[0] == body.user.username;
});
value1 = vArray [1];
console.log("v: " + vArray[1]);
});
return value1;
});
return { val1: value1, val2: value2};
}
In other words, I see the correct value in the line
console.log("v: " + vArray[1]);
but it's like it's not being assigned to value1 in the line
value1 = vArray [1];
or at least the value is lost after it exits the method Authenticate. How can a return that value to where the call to createSpreadsheetEntry is done?
Thanks in advance. Guillermo.