【问题标题】:Run function asynchronously in Google Apps Script在 Google Apps 脚本中异步运行函数
【发布时间】:2020-07-09 02:17:46
【问题描述】:

我正在制作一个调用 GAS 函数的 Slack 机器人。一切正常,除了 Slack 显示一条错误消息,因为它在调用 API 时只等待 3 秒的响应。

谁能帮我弄清楚如何异步运行everyDay2,以便我可以在响应完成之前返回它。我已经尝试过 Promises 和回调,但我无法解决它。

function doPost(e){

  const promise = new Promise(everyDay2);

  return ContentService.createTextOutput('thinking...');

}

【问题讨论】:

  • 我试过了。如果我这样做:let asyncFunction = async function() { everyDay2() }; return ContentService.createTextOutput('thinking...'); 显然everyDay2 永远不会被调用。当我这样做时:let asyncFunction = async function() { everyDay2() };asyncFunction();return ContentService.createTextOutput('thinking...'); 似乎asyncFunction 同步运行并且响应发送得太晚了。我错过了什么吗?

标签: javascript asynchronous google-apps-script promise slack-api


【解决方案1】:

承诺不起作用。使用triggers instead:

function doPost(e) {
  runAfter1s('everyDay2');
  return ContentService.createTextOutput('thinking...?');
}

const runAfter1s = func =>
  ScriptApp.newTrigger(func)
    .timeBased()
    .after(1000)
    .create();

确保在触发后删除everyDay2内创建的触发器。

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多