有没有办法在继续代码之前等待异步应用程序脚本函数调用?

Is there a way to wait for asynchronous apps-script function calls before continuing with code?

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

我拿了一份模板文档,制作副本,编辑副本,然后通过电子邮件发送。 不幸的是,在电子邮件代码运行之前编辑还没有完成,所以电子邮件在编辑完成之前附加了复制的文档。有解决办法吗?

//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() 不相关,因为我们没有使用电子表格。

答案:

使用 DocumentAppsaveAndClose() 方法在继续之前强制更改。

更多信息:

根据 Apps 脚本文档:

Saves the current Document. Causes pending updates to be flushed and applied.

The saveAndClose() method is automatically invoked at the end of script execution for each open editable Document.

A closed Document can't be edited. Use DocumentApp.openById() to reopen a given document for editing.

实施:

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 方法拆分为单独的函数也有助于解决此问题。

参考文献: