Eric
Eric

Reputation: 262

Why am I getting an undefined value when calling these scripts in Google App Maker?

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!

Upvotes: 0

Views: 211

Answers (1)

Pavel Shkleinik
Pavel Shkleinik

Reputation: 6347

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

Upvotes: 3

Related Questions