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

Asynchronous 在继续编写代码之前,是否有方法等待异步应用程序脚本函数调用?,asynchronous,google-apps-script,gmail,drive,Asynchronous,Google Apps Script,Gmail,Drive,我正在尝试复制驱动器中的文档,编辑并邮寄它。基本上就像邮件合并 我拿了一份模板文档,制作了一份副本,编辑了副本,然后通过电子邮件发送。 不幸的是,在电子邮件代码运行之前,编辑尚未完成,因此电子邮件会在编辑之前附加复制的文档。有办法解决这个问题吗 //make a copy of the template var templateCopy = DriveApp.getFileById(templateID).makeCopy('newFile', DriveApp.getFolderById(

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

我拿了一份模板文档,制作了一份副本,编辑了副本,然后通过电子邮件发送。 不幸的是,在电子邮件代码运行之前,编辑尚未完成,因此电子邮件会在编辑之前附加复制的文档。有办法解决这个问题吗

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

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

更多信息: 根据应用程序脚本文档:

保存当前的
文档
。导致刷新和应用挂起的更新

对于每个打开的可编辑
文档
,脚本执行结束时会自动调用
saveAndClose()
方法

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

实施:
函数documentStuff(){
//复制模板
var templateCopy=DriveApp.getFileById(templateID).makeCopy('newFile',
DriveApp.getFolderById(targetFolderID)
);
//选择模板的内容
var copyBody=DocumentApp.openById(templateCopy.getId());
//替换文本:设置日期
replaceText(“%DATE%”,“today”);
copyBody.saveAndClose();
sendMail(targetAddress,DocumentApp.openById(templateCopy.getId());
}
函数sendMail(targetAddress,文件){
//发送电子邮件-收到的电子邮件没有日期替换
//它仍然包含%DATE%标记
GmailApp.sendmail(targetAddress,'鸡蛋','鸡蛋'{
附件:[
file.getAs(MimeType.PDF)]
}
);
}
将Document和Gmail方法拆分为单独的函数也有助于解决这个问题

参考资料:

可能重复的@TheMaster不
SpreadsheetApp.flush()
仅适用于电子表格?OP的代码片段没有引用任何google工作表…您可以在
replaceText
之后放置一个
copyBody.saveAndClose()
。这可能就是@TheMaster的意图。非常好的建议,谢谢。Flush无法工作,因为它不在工作表中,但saveAndClose()正在执行此任务。非常感谢,谢谢拉法。这就是我在将幻灯片附加到电子邮件之前需要保存和关闭的内容,否则它们只是空幻灯片。