0

I do not understand why when I am calling a ServerScript method from a ClientScript method, I am getting a value of undefined.

ClientScript:

    function clientScript() {
      var message;
      message = google.script.run.test();
      console.log("Message: " + message);
    }

ServerScript:

    function serverScript() {
       return "hello";
    }

I expected the console to print: Message: hello. However, I am getting this printed to my console: Message: undefined. Why am I getting an undefined value in my ClientScript method when I am returning a defined value in my ServerScript method? Thank you!

Eric
  • 264
  • 1
  • 5
  • 15
  • Possible duplicate of [Use variable value from .gs file in custom HTML sidebar](https://stackoverflow.com/questions/47306725/use-variable-value-from-gs-file-in-custom-html-sidebar) – tehhowch Jun 20 '18 at 06:21

1 Answers1

3

Because server calls are asynchronous. In order to handle server response you need to pass callback. Here is a snippet from Apps Script docs:

function onSuccess(numUnread) {
  console.log(numUnread);
}

google.script.run.withSuccessHandler(onSuccess)
    .getUnreadEmails();

Just in case AMs docs interpretation of the same thing - https://developers.google.com/appmaker/scripting/client#call_a_server_script

Pavel Shkleinik
  • 6,298
  • 2
  • 24
  • 36