简体   繁体   中英

Pass an Array from Code.gs to Javascript Google App Script

I have a function that returns an array of objects in my Code.GS file that I want to pass onto a variable in my index.html file to use in JavaScript. But for some reason, the variable is not being updated, and it seems to me the onSuccess function is not being run.

Code.gs file

        function getData(){
        var dates = [{
                title  : 'obj',
                time  : '2018-07-13T',
                color: '#C2185B'
            },
            {
                title  : 'obj2',
                start  : '2018-07-19',
                end    : '2018-07-20',
            },
          ];
      return dates;
    }

index.html file:

<script>
 var dates;

function onSuccess(array) {
   dates = array;
}
google.script.run.withSuccessHandler(onSuccess).getData();
<!-- code that requires dates array-->
</script>

All google.script.run invocations are asynchronous, meaning it takes time for the function to get back a response from the Apps Script server. Meanwhile, the code that requires the dates array is synchronous and is executing before the dates variable gets updated. So the code that requires the dates array should probably live inside your onSuccess handler.

If you really want to get fancy you can even leverage Promises to make your code asynchronous and sequentially readable at the same time.

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