0

I'm making a Slack bot that calls a GAS function. Everything is working except Slack shows an error message because it only waits 3 seconds for a response when calling an API.

Can anyone help me to work out how to run everyDay2 asynchronously so that I can return the response before it's finished. I've tried Promises and callbacks but I can't solve it.

function doPost(e){

  const promise = new Promise(everyDay2);

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

}
TheMaster
  • 45,448
  • 6
  • 62
  • 85
Dave Cook
  • 617
  • 1
  • 5
  • 17
  • 1
    Does this answer your question? [Does Google Apps Script V8 engine support Promise?](https://stackoverflow.com/questions/61578224/does-google-apps-script-v8-engine-support-promise) – Rubén Jul 09 '20 at 02:30
  • I tried that. If I do this: `let asyncFunction = async function() { everyDay2() };` `return ContentService.createTextOutput('thinking...');` Obviously `everyDay2` is never called. When I do this: `let asyncFunction = async function() { everyDay2() };` `asyncFunction();` `return ContentService.createTextOutput('thinking...');` It seems like `asyncFunction` runs synchronously and the response is sent too late. Am I missing something? – Dave Cook Jul 09 '20 at 02:37

1 Answers1

5

Promises doesn't work. Use triggers instead:

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

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

Make sure to delete the created trigger inside everyDay2 after being triggered.

TheMaster
  • 45,448
  • 6
  • 62
  • 85