简体   繁体   中英

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

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?

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
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM