如何以正确的顺序执行函数G脚本

时间:2018-08-23 08:34:14

标签: html google-apps-script google-sheets google-sheets-api

已经完成我的项目,但是又出现了另一个问题。 当我尝试在边栏中单击按钮后运行多个功能时,其中某些功能的执行速度比其他功能快。有人可以帮忙解决吗?

<!DOCTYPE html>
    <html>
  <head>
    <base target="_top">

<style>
body {
    background-color: #fafab6; 
    }


</style>

<form name="submit-to-google-sheet">

   <BR>

  <label for="Cinnost">Cinnost: </label>
  <select name="Cinnost" type="text" placeholder="Cinnost">
   <option value="Konstrukce">Konstrukce</option>
   <option value="Montaz">Montaz</option>
   <option value="Management">Uklid</option>
   <option value="Udrzba / uklid">Udrzba / uklid</option>
  </select>

  <BR>
  <BR>
   Zvol cas:

  <input type="Time" name="usr_time" placeholder="Time">

  <BR>
  <BR> 
  <BR>
  <BR>
  <button type="submit">Send</button>

  <input type="reset">
</form>


<script>

 function pokusnak() {

 google.script.run.copykomplet();

 } 

  const scriptURL = 'https://script.google.com/macros/s/AKfycbx0rzbLMsXKQ1C3--qP-wHtcFdfvmOG--y_Qpk0xc43EqtUdSeF/exec'
  const form = document.forms['submit-to-google-sheet']

  form.addEventListener('submit', e => {
    e.preventDefault()
    fetch(scriptURL, { method: 'POST', body: new FormData(form)})
      .then(response => console.log('Success!', response))
      .catch(error => console.error('Error!', error.message))

   //executes before the lines above
   pokusnak();
   // when left here to close the sidebar executes before the lines before and stops the program
   google.script.host.close();
  } 
  )

我需要在G纸上张贴1号,然后运行“ pokusnak”函数,该函数会通过Copykomplet函数触发google.script.run,请在下面找到。然后关闭侧边栏。

问题是函数未按正确的顺序执行。

Code.gs:

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()


function onOpen()
{
  SpreadsheetApp.getUi().createMenu('My Tools')
    .addItem('createTextEntryForm', 'createTextEntryForm')
    .addToUi();

  loadSideBar();
  SpreadsheetApp.getUi().createMenu('My Menu').addItem('loadSidebar', 'loadSideBar').addToUi();  
}


function intialSetup () {
  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  scriptProp.setProperty('key', activeSpreadsheet.getId())
}

function doPost (e) {
  var lock = LockService.getScriptLock()
  lock.tryLock(10000)

  try {
    var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
    var sheet = doc.getSheetByName(sheetName)

    var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
    var nextRow = sheet.getLastRow() + 1

    var newRow = headers.map(function(header) {
      return header === 'timestamp' ? new Date() : e.parameter[header]
    })

    sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  catch (e) {
    return ContentService
      .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
      .setMimeType(ContentService.MimeType.JSON)
  }

  finally {
    lock.releaseLock()
  }

}

function loadSideBar()
{

 var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getActiveSheet(),
      ui = SpreadsheetApp.getUi(),
      cell = sheet.getCurrentCell(),
      val = cell.getValue(),
      col = cell.getColumn(),
       row = cell.getRow(),
      zacni = sheet.getRange(row, col);

  if (col === 7 && row > 7 && val !== 'Pocet dilu: ') {  


  var userInterface=HtmlService.createHtmlOutputFromFile('index');//sidebar for html and formBar for form
  SpreadsheetApp.getUi().showSidebar(userInterface);

 // doPost ();

  } else ui.alert('Nevybral jsi žádný díl, zkus to znovu'); 

}



function delampokus2() {

  var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getActiveSheet(),
      ui = SpreadsheetApp.getUi(),
      cell = sheet.getCurrentCell(),
      val = cell.getValue(),
      col = cell.getColumn(),
       row = cell.getRow(),
      zacni = sheet.getRange(row, col);

  if (col === 7 && row > 7 && val !== 'Pocet dilu: ') {

       var sss4 = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
       var ss4 = sss4.getSheetByName('Otevrene zakazky');
       var radek4 = row
       var source4 = ss4.getRange (radek4,2);
       var destSheet4 = sss4.getSheetByName('Sheet2');
       var destRange4 = destSheet4.getRange(destSheet4.getLastRow(),4);
       source4.copyTo (destRange4, {contentsOnly: true}); 

       var source5 = ss4.getRange (radek4,3);
       var destSheet5 = sss4.getSheetByName('Sheet2');
       var destRange5 = destSheet5.getRange(destSheet5.getLastRow(),5);
       source5.copyTo (destRange5, {contentsOnly: true});        

       var source6 = ss4.getRange (radek4,7);
       var destSheet6 = sss4.getSheetByName('Sheet2');
       var destRange6 = destSheet6.getRange(destSheet6.getLastRow(),6);
       source6.copyTo (destRange6, {contentsOnly: true}); 

       var source7 = ss4.getRange (radek4,9);
       var destSheet7 = sss4.getSheetByName('Sheet2');
       var destRange7 = destSheet7.getRange(destSheet7.getLastRow(),7);
       source7.copyTo (destRange7, {contentsOnly: true}); 

       var destSheet8 = sss4.getSheetByName('Sheet2');
       var destRange8 = destSheet8.getRange(destSheet8.getLastRow(),8);
       destRange8.setValue('Petr')     

    ui.alert('vsetko okej');

  } else ui.alert('Nevybral jsi žádný díl, zkus to znovu');    

}


function moveValuesOnly () {

  var sss = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
  var ss = sss.getSheetByName('Sheet1');

  // ss = SpreadsheetApp.getActiveSpreadsheet ();
  var radek = ss.getLastRow()
  var source = ss.getRange (radek,1);
  var destSheet = sss.getSheetByName('Sheet2');

  // "Sheet1!F1:H3"
  // ss.getRange (radek,1);

  var destRange = destSheet.getRange(destSheet.getLastRow()+1,1);
  source.copyTo (destRange, {contentsOnly: true});
  //source.clear ();


   var sss2 = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
  var ss2 = sss2.getSheetByName('Sheet1');
    var radek2 = ss2.getLastRow()
  var source2 = ss2.getRange (radek2,2);
  var destSheet2 = sss2.getSheetByName('Sheet2');

  var destRange2 = destSheet2.getRange(destSheet2.getLastRow(),2);
  source2.copyTo (destRange2, {contentsOnly: true});


     var sss3 = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
  var ss3 = sss3.getSheetByName('Sheet1');
    var radek3 = ss3.getLastRow()
  var source3 = ss3.getRange (radek3,3);
  var destSheet3 = sss3.getSheetByName('Sheet2');
   var destRange3 = destSheet3.getRange(destSheet3.getLastRow(),3);
  source3.copyTo (destRange3, {contentsOnly: true});
}


function copykomplet () {

    var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getActiveSheet(),
      ui = SpreadsheetApp.getUi(),
      cell = sheet.getCurrentCell(),
      val = cell.getValue(),
      col = cell.getColumn(),
       row = cell.getRow(),
      zacni = sheet.getRange(row, col);

  var sss = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
  var ss = sss.getSheetByName('Sheet1');
  var radek = ss.getLastRow()
  var source = ss.getRange (radek,1);
  var destSheet = sss.getSheetByName('Sheet2');
  var destRange = destSheet.getRange(destSheet.getLastRow()+1,1);
  source.copyTo (destRange, {contentsOnly: true});
  //source.clear ();

  var sss2 = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
  var ss2 = sss2.getSheetByName('Sheet1');
  var radek2 = ss2.getLastRow()
  var source2 = ss2.getRange (radek2,2);
  var destSheet2 = sss2.getSheetByName('Sheet2');
  var destRange2 = destSheet2.getRange(destSheet2.getLastRow(),2);
  source2.copyTo (destRange2, {contentsOnly: true});

  var sss3 = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
  var ss3 = sss3.getSheetByName('Sheet1');
  var radek3 = ss3.getLastRow()
  var source3 = ss3.getRange (radek3,3);
  var destSheet3 = sss3.getSheetByName('Sheet2');
  var destRange3 = destSheet3.getRange(destSheet3.getLastRow(),3);
  source3.copyTo (destRange3, {contentsOnly: true});      

       var sss4 = SpreadsheetApp.openById('1_yfU1PuBds5KcsqG-iPugpjeYEOX5sdXuFXIuLAIxok');
       var ss4 = sss4.getSheetByName('Otevrene zakazky');
       var radek4 = row
       var source4 = ss4.getRange (radek4,2);
       var destSheet4 = sss4.getSheetByName('Sheet2');
       var destRange4 = destSheet4.getRange(destSheet4.getLastRow(),4);
       source4.copyTo (destRange4, {contentsOnly: true}); 

       var source5 = ss4.getRange (radek4,3);
       var destSheet5 = sss4.getSheetByName('Sheet2');
       var destRange5 = destSheet5.getRange(destSheet5.getLastRow(),5);
       source5.copyTo (destRange5, {contentsOnly: true});        

       var source6 = ss4.getRange (radek4,7);
       var destSheet6 = sss4.getSheetByName('Sheet2');
       var destRange6 = destSheet6.getRange(destSheet6.getLastRow(),6);
       source6.copyTo (destRange6, {contentsOnly: true}); 

       var source7 = ss4.getRange (radek4,9);
       var destSheet7 = sss4.getSheetByName('Sheet2');
       var destRange7 = destSheet7.getRange(destSheet7.getLastRow(),7);
       source7.copyTo (destRange7, {contentsOnly: true}); 

       var destSheet8 = sss4.getSheetByName('Sheet2');
       var destRange8 = destSheet8.getRange(destSheet8.getLastRow(),8);
       destRange8.setValue('Petr')     


       ui.alert('Zaznam pridan');



}

1 个答案:

答案 0 :(得分:1)

抓取与google.script.run是异步的。这意味着对fetch的调用会启动一个操作,但不会等待它完成。您正在关闭对话框,所以它永远不会完成。如果要在操作完成后执行某些操作,则必须提供一个将在完成时运行的回调函数。

对于fetch().then()函数是您提供回调的方式。

您的postnak()函数正在调用google.script.run.copyKomplet(),这也是异步的,因此您不能调用google.script.host.close()直到完成。使用google.script.runwithSuccessHandler()提供withFailureHandler()的回调:

form.addEventListener('submit', e => {
  e.preventDefault()
  fetch(scriptURL, { method: 'POST', body: new FormData(form)})
  .then(response => {
    console.log('Success!', response);
    google.script.run
    .withSuccessHandler(()=>google.script.host.close())
    .withFailureHandler((e)=>alert("Error:" + e))
    .copykomplet();
  })
  .catch(error => console.error('Error!', error.message))
} 

正如其他人建议的那样,值得花一些时间来了解它在JavaScript / Google Apps脚本中的工作方式,因为异步调用是这些技术工作方式的核心部分。