Google Apps Script withSuccessHandler is running before function fully executes

拟墨画扇 提交于 2020-01-16 16:57:01

问题


I have two files in an Apps Script project. One is a .gs file acting as a "server" and one is a .html file containing JavaScript as per Google's Apps Script guidelines.

Everything has been going swimmingly for the first 40 hours of development on this project. I have the following line of code outside of any function, in between two tags in the .html file:

google.script.run.withSuccessHandler(setSheetData).getSheetData();

Documentation: https://developers.google.com/apps-script/guides/html/reference/run#withSuccessHandler(Function)

According to the documentation, getSheetData() should first execute in the .gs file, and return a value that is then passed into setSheetData which exists in the .html file.

Server file:

  function getSheetData() {
  var ss = SpreadsheetApp.getActive();
  var activeSheet = ss.getActiveSheet();
  var sheetName = activeSheet.getName();
  var sheetVals = activeSheet.getDataRange().getValues();
  return [sheetName, sheetVals];
}

Html file:

function setSheetData(data) {
    alert(data);
    sheetName = data[0];
    sheetData = data[1];
    headers = sheetData[0];
    document.getElementById('sheetLook').innerHTML = 'Looking at sheet: ' + sheetName;
}

How I know it is a matter of execution speed: Currently the alert() call just prints out null. The sheet it is drawing from contains 4 rows of data. However, all other things remaining the same, if I simply am looking at a sheet with 0-1 rows of data, it correctly alerts the entire data vals.

Inside of getSheetData() if I add Logger.log(sheetVals) it correctly logs the entire sheet's data regardless of size. The issue is that the successhandler is executing before it has time to evaluate.


回答1:


Possible cause(s):

  • Illegal return values in rows 3-4 of data
  • No active sheet is present.

Solution:

  • Avoid returning illegal values like Date objects. Or JSON.stringify() them before returning to client.
  • getSheetByName or number instead of getting it by activeness.

References:

  • google.script.run § myFunction § return


来源:https://stackoverflow.com/questions/57274328/google-apps-script-withsuccesshandler-is-running-before-function-fully-executes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!