Reputation: 133
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>
Upvotes: 1
Views: 1100
Reputation: 8964
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.
Upvotes: 1