google.script.run.withSuccessHandler(函数)不返回数据

时间:2020-10-29 10:30:43

标签: javascript google-apps-script google-workspace

我正在使用G-suite,并使用“ google.script.run”功能。我无法从将我的数据从服务器获取到客户端的函数中获取数据或设置数据...我可以将数据设置为#myId的DOM并检查它,但我想在后台进行...任何想法为什么这不起作用?

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

我需要能够使用常规数据设置this.data ...或者至少从this.getData()返回它们

更新

我有

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

我的输出始终是“给我测试”,看来辅助函数无法访问GLOBAL SCOPE变量...

1 个答案:

答案 0 :(得分:1)

问题:

google.script.run的时差或异步性质:当时submitData被执行,this.datafalse,因为getData()尚未完成执行。

                                                 ➚ 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

解决方案:

在调用this.submitData()之后调用helper

摘要:

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

参考文献: