首页 > 解决方案 > 需要在 Slack App Node.js 的异步函数中获取 REST API

问题描述

我正在尝试为 Slack 创建一个在调用命令时调用外部 api 的应用程序。我做了以下事情。但问题是 Slack 框架使用了一个await

app.command("/command", async({ ack, payload, context })=>{
  ack();
  var details;
  try{
    apiHandler(function(details) {
    const result = await app.client.chat.postMessage({  //<--- error here
      token: context.botToken,
      channel: payload.channel_id,
      blocks: [
        {
          type: "section",
          text: {
            type: "mrkdwn",
            text: details
          },
        }
      ],
      text: "Message from Test App"
    });
      console.log(details);
    });
  }catch(error)
  {
    console.error(error);
  }
});

//helper function:
function apiHandler(callback) {
  let XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
  let xhr = new XMLHttpRequest;
     xhr.open("GET","API-URL",true);
     xhr.onload = function()
     {
         if(this.status===200){
           callback(JSON.parse(this.responseText););
         }
       }
       xhr.send();
}

当我启动节点时,我得到以下信息:

SyntaxError: await 仅在异步函数中有效

我对 node.js 很陌生,我完全不知道该怎么做

标签: javascriptnode.jsslack

解决方案


将 async 关键字放在apiHandler(async function(details) {


推荐阅读