首页 > 解决方案 > 将 Apps Script HTML 中的客户端`JavaScript fetch().then()` 转换为 google.script.run

问题描述

这个问题在以下 Stack Overflow 链接中得到解答:

等待google服务端函数解析

此问题特定于google.script.runAPI for Apps 脚本。我需要使用google.script.run.serverFncName()调用在服务器上运行代码,然后在运行下一个函数之前等待返回。我尝试转换的代码示例使用 JavaScript fetch().then()

我尝试转换的代码示例:

<script>
  window.some_Object_Name = {

    innerNameOne : function() {
                   return fetch('The URL goes here for HTTP Request', {
                     method: 'post'
                   }).then(function(response_Back_From_Request) {
                     return res.json()response_Back_From_Request;
                   });
                },
  }
</script>

需要使用google.script.run.myServerAppsScriptFnc()而不是fetch(url) 显然,类似以下的内容不起作用,但我出于说明目的展示它:

<script>
  window.some_Object_Name = {

    innerNameOne : function() {
                   google.script.run
                     .withSuccessHandler(function(response_Back_From_Request) {return response_Back_From_Request;})
                     .myServerAppsScriptFnc({method:'post'});
                   .then(function(response_Back_From_Request) {
                     return response_Back_From_Request;
                   });
                },
  }
</script>

我假设我需要使用Promise

<script>
  window.makeCallToGoogleServer = function() {
  
    google.script.run
      .withSuccessHandler(function(rtrnFromServer) {return rtrnFromServer;})
      .myServerAppsScriptFnc({method:'post'});


  }

  window.some_Object_Name = {

    innerNameOne : function() {
                   let myPromise = new Promise(function(myOnSuccessFnc) {
                     
                     makeCallToGoogleServer();
                       
                     myOnSuccessFnc(response_Back_From_Request);
                     
                   });


                myPromise.then(
                  return fromFirstFunc;
                 );
              }
  }
</script>

标签: google-apps-scriptpromise

解决方案


推荐阅读