Search code examples
javascriptgoogle-apps-scriptweb-applicationspromiseasync-await

Easiest way to wait for google server-side function to resolve


I need the client side code to wait for the called server side (google.script.run) function to complete before running any more code.

The withSuccessHandler(successFunc) does not cause lines of code that are after the server call to wait.

What I've done:

async function func(){
   await google.script.run.withSuccessHandler(myFunc).serverFunc();
   console.log("done");
}
func();

How can the code wait to execute the console.log line until after the server side function resolves?


Solution

  • How about this answer? Please think of this as just one of several answers.

    Pattern 1:

    In this pattern, after serverFunc was run, myFunc is run. At that time, console.log("done") is run in myFunc.

    function myFunc() {
       console.log("done");
    }
    
    function func(){
       google.script.run.withSuccessHandler(myFunc).serverFunc();
    }
    
    func();
    

    Pattern 2:

    In this pattern, Promise was used. When you run func(), you can see ok and done in order.

    function myFunc() {
      return "ok";
    }
    
    async function func() {
      await new Promise(r => {
        google.script.run.withSuccessHandler(r).serverFunc();
      });
      const res = myFunc();
      console.log(res);
      console.log("done");
    }
    
    func();
    

    Note:

    • If you test above samples, please set the function of serverFunc() at Google Apps Script side.
    • This is a simple sample script. So please modify this for your actual situation.

    References:

    If this was not the direction you want, I apologize.

    Added:

    If you want to use the values from serverFunc at myFunc, how about the following sample script?

    Sample script:

    function myFunc(nice) {
      doStuffs(nice);
    
      return "ok";
    }
    
    async function func() {
      const e = await new Promise(r => {
        google.script.run.withSuccessHandler(r).serverFunc();
      });
      const res = myFunc(e);
      console.log(res);
      console.log("done");
    }
    
    func();
    
    • In this script, the returned value from myFunc can be retrieved by res.