简体   繁体   中英

google.script.run.withSuccessHandler(function) not returning data

I'm working with G-suite and using "google.script.run" function. I can't fetch or set data out of the function that get's me data to client from server...I can set data to DOM for #myId and check that but I'd like to do it on background...any idea why is this not working?

function Class(){
  this.data = false;

  this.getData = function(){
    google.script.run.withSuccessHandler(helper).getData();
      function helper(data){
        $('#myId').html('data'); // => works...
        this.data = data; // => does not work...
        return data; // => does not work...
      }
  }

  this.submitData = function(){
    if(this.data === false){
      alert('no data');
    }
    else{
      ...code...
    }
  }

  this.run = function(){
    this.getData();
    this.submitData(); // => always get false;
  }
}

I need to be able to set this.data with with regular data...or atleast return them from this.getData()

UPDATE

I've got

this.getData = function(){
  var testOuput = 'give me test';
    google.script.run.withSuccessHandler(helper).getData();
      function helper(data){
        testOuput = 'give me something else';
      }
  return testOutput;   
}

this.run {
  alert(this.getData());
}

this.run() // => runs on button click

My output is always "give me test" It looks like helper function is not able to access GLOBAL SCOPE variables...

Issue:

Time difference or Async nature of google.script.run : At the time, submitData executes, this.data is false , because getData() hasn't finished executing.

                                                 ➚ Server executes `getData()` => Calls `helper(datafromServer)` after execution 
                                               ➚  
`this.run` => `this.getData()` => Server called with `google.script.run` and  returns void immediately 
                                                (Client will not wait for server/async) 
                                               ➘ `this.submitData()` called => `helper()` hasn't finished executing. `this.data` is still false

Solution:

Call this.submitData() after helper is called.

Snippet:

  function helper(data){
    $('#myId').html('data'); // => works...
    this.data = data; 
    this.submitData();// => works
  }

References:

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