从使用 google.script.run 的嵌套函数取回变量

Getting a Variable back from a Nested Function that uses google.script.run

我确信我即将解决这个问题。我做了一些研究,并不断发现一些例子,这些例子表明我可以在嵌套函数中使用局部变量,但反过来只能使用一些东西(从嵌套函数中取回变量)。最重要的是,我正在与 google.script.run.withSuccessHandler() 合作,这让我很困惑(或者至少让我很困惑)

我需要取回 xRates,以便在函数 "updateSidebarValues" 中使用它。我曾尝试使用闭包,但老实说,在添加 withSuccessHandler 元素时,我真的不明白该怎么做。

我改写了这个:(错了,但我一定很接近?)

function updateSidebarValues(salesTotals) {

       var valueToPass = document.getElementById('reportSelect').value;
  google.script.run.withSuccessHandler(RatesGetter).getXrates(valueToPass);

 function RatesGetter(xRates) {
  alert('YAY!!!! This is the variable we need from Code.gs : ' + xRates);
 }

   ..... Do other stuff with xRates

}

我的警报有效...它显示了我的代码文件的正确结果...但是当我稍后尝试使用 xRates 时,告诉我它未定义:(

答案很简单,这里:function RatesGetter(xRates) {...} xRates是函数的参数,只能在这个方法内部访问。它将在 callback(xRates) 内部传递,但在您写“......用 xRates 做其他事情”的地方将无法访问它。

您实际上遇到的不仅仅是范围界定问题。 google.script.run.withSuccessHandler() 似乎是异步的,所以它得到的结果不会在同一个事件循环中发生。因此,即使您可以解决范围问题,您也会在定义值之前尝试访问这些值。您可以创建另一个函数并从回调中调用它。例如:

function updateSidebarValues(salesTotals) {

    var valueToPass = document.getElementById('reportSelect').value;
    google.script.run.withSuccessHandler(RatesGetter).getXrates(valueToPass);

    function RatesGetter(xRates) {
        alert('YAY!!!! This is the variable we need from Code.gs : ' + xRates);
        doOtherStuff(xRates)
    }
    function doOtherStuff(xRates) {
        //… Do other stuff with xRates
    }
}

或者您可以直接在 RatesGetter() 中做其他事情。