在继续执行代码之前,是否有等待异步应用程序脚本函数调用的方法?

问题描述 投票:1回答:1

我正在尝试复制驱动器中的文档,对其进行编辑并将其邮寄。基本上就像邮件合并。

我获取模板文档,制作副本,编辑副本,然后通过电子邮件发送。不幸的是,在电子邮件代码运行之前,编辑尚未完成,因此电子邮件在进行编辑之前会附加复制的文档。有没有解决的办法?

//make a copy of the template
var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile',   DriveApp.getFolderById(targetFolderID));

//select the contents of the template
var copyBody = DocumentApp.openById(templateCopy.getId())

//replace text: set the date
copyBody.replaceText("%DATE%",'today')

//send email - the email that arrives does not have the date substitution, it still contains the %DATE% tag
  GmailApp.sendEmail(targetAddress, 'eggs', 'eggs', {attachments:[copyBody.getAs(MimeType.PDF)]});

有关可能重复项的编辑:SpreadsheetApp.flush()与我们无关,因为我们不使用电子表格。

asynchronous google-apps-script gmail drive
1个回答
0
投票

答案:

使用saveAndClose()DocumentApp方法强制更改,然后继续。

更多信息:

根据Apps脚本文档:

保存当前的Document。导致刷新并应用待处理的更新。

saveAndClose()方法在脚本执行结束时自动为每个打开的可编辑Document调用。

关闭的Document无法编辑。使用DocumentApp.openById()重新打开给定的文档进行编辑。

实施:

function documentStuff() {
  //make a copy of the template
  var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile',   
    DriveApp.getFolderById(targetFolderID)
  );

//select the contents of the template
  var copyBody = DocumentApp.openById(templateCopy.getId());

  //replace text: set the date
  copyBody.replaceText("%DATE%",'today');
  copyBody.saveAndClose();

  sendMail(targetAddress, DocumentApp.openById(templateCopy.getId()));
}

function sendMail(targetAddress, file) {
  //send email - the email that arrives does not have the date substitution
  // it still contains the %DATE% tag
  GmailApp.sendEmail(targetAddress, 'eggs', 'eggs', {
    attachments: [
      file.getAs(MimeType.PDF)]
    }
  );
}

将Document和Gmail方法拆分为单独的功能也可以帮助解决此问题。

参考:

© www.soinside.com 2019 - 2024. All rights reserved.