【问题标题】:google.script.run.withSuccessHandler(function) not returning datagoogle.script.run.withSuccessHandler(function) 不返回数据
【发布时间】:2020-10-29 10:30:43
【问题描述】:

我正在使用 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 变量...

【问题讨论】:

  • 如果你在辅助函数中console.log(this),输出是什么?它可能指向不同的对象,因此请尝试以下操作:google.script.run.withSuccessHandler(helper.bind(this)).getData();
  • 您需要等到数据检索完毕。
  • @Reyno - 没有帮助...
  • 我的输出总是“给我测试”你是怎么得到输出的?
  • 也许你的 Successhandler 永远不会因为 Apps 脚本函数 getData() 失败而被调用?实现一个FailureHandler 来验证。另外,如果您认为这可能是问题的原因,请提供 getData() 的代码以进行故障排除

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


【解决方案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

解决方案:

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

片段:

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

参考资料:

【讨论】:

  • 我明白你的意思,但事实并非如此......也许我把函数运行这两个函数是我的错,但实际上我在至少一分钟阅读之前运行函数 getData事实上,我可以在屏幕上看到它们被保存在 DOM 中......用户使用这些数据在客户端站点上进行操作,也许一分钟后我运行提交功能......
  • @Orbit 您能否编辑您的问题以提供minimal reproducible example
猜你喜欢
  • 2019-10-22
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 2018-09-30
  • 2019-02-28
相关资源
最近更新 更多