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

用户1412705

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

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

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

拉法·吉列尔莫

回答:

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

参考:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有没有办法在应用程序被杀死或移至后台之前立即调用特定代码?

有没有办法让 Racket Web 应用程序中的按钮调用文件中定义的函数?

有没有办法从代码写入自定义应用程序配置配置

有没有办法在React Native应用程序中使用我的Python代码?

有没有办法查看android照片应用程序的源代码?

有没有办法从网络拦截中隐藏应用程序网络调用

有没有办法等待诺言才能继续?

关闭调用终端的应用程序后,有没有办法让该应用程序运行?

有没有办法让函数调用“继续”影响其调用者中的循环?

有没有办法等待在webflux代码中的异步方法结果

有没有办法编写响应onkeypress事件的异步等待代码?

有没有办法在调用“zsh”后继续执行脚本?

有没有办法从Java应用程序回调到Rails应用程序?

有没有办法在调用 nodejs 中的控制器之前调用函数

有没有办法在iOS应用程序崩溃时采取措施,从而执行代码?这可能吗?

有没有办法知道哪个应用程序通过代码在ubuntu中产生声音(音频输出)?

有没有办法在不更改代码或文件的情况下重新加载烧瓶应用程序?

有没有办法跟踪Web应用程序在mysql服务器中进行的调用?

有没有办法在 iOS 14 应用程序生命周期中调用 SceneDelegate 方法?

有没有办法在应用程序被另一个应用程序取代之前获得通知?

有没有办法从chrome扩展程序启动chrome打包的应用程序

有没有办法从C应用程序与驱动程序进行通信?

有没有办法在您的Rails应用程序中收集所有模型?

有没有办法改变ClickOnce“应用程序有更新”自动消息?

有没有办法回滚所有Django应用程序的迁移?

有没有办法在执行下一个命令之前等待(在 bash 脚本中)python 程序(在新终端中启动)结束?

有没有办法使用 python 脚本故意多次调用 lambda 函数?如何?

有没有办法在“Flutter web”应用程序的代码中获取用于启动应用程序的 URL?

有没有办法调用部分函数