Dave Cook
Dave Cook

Reputation: 717

Run function asynchronously in Google Apps Script

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...');

}

Upvotes: 0

Views: 3509

Answers (1)

TheMaster
TheMaster

Reputation: 50383

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.

Upvotes: 5

Related Questions