Home > Mobile >  google.script.run function won't write to JavaScript global variable using await
google.script.run function won't write to JavaScript global variable using await

Time:07-06

I have been having trouble lately with global variables as well as using async functions like "await" (which I am new to) in Javascript with Apps Script.

Here's my JavaScript code:

let patientData = {};

$(document).ready(function() {
  loadPatientData(); //I want to wait for this to complete

  google.script.run.logThis(patientData.names); //Returns null
})

async function loadPatientData() {

  //Get the data from an array in the .gs file, pass it to variable "a"
  const a = await new Promise(r => {
    google.script.run.withSuccessHandler(r).getPatientData();
  });

  //Pass that data to global variable
  //If I log patientData.names here, it returns with the array data
  patientData.names = a;
}

What I want to be able to do is to wait for the google.script.run.withSuccessHandler function to complete and then pass the resulting array data to my patientData.names variable. As seen with my comments in the code, the array is passed to the global variable inside loadPatientData(), but not in (document).ready().

getPatientData() returns an array.

Right now I am logging this with a function in my .gs file called logThis() which just uses Logger.log() to print data to the Execution Log.

patientData.names comes back as null in the Execution Log. So what am I doing wrong?

CodePudding user response:

The calling function also needs to be async:

$(document).ready(async function() {
  await /*I want to wait for this to complete => so wait*/loadPatientData();
  google.script.run.logThis(patientData.names); //Returns good
})
  • Related