Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Pass value of variable from inner function to container function in javascript

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!