需要在 Slack App Node.js 的异步函数中获取 REST API
Need to GET a REST API within async function in Slack App Node.js
我正在尝试为 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 is only valid in async function
我是 node.js 的新手,完全不知道该怎么做
将 async 关键字放在 apiHandler(async function(details) {
我正在尝试为 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 is only valid in async function
我是 node.js 的新手,完全不知道该怎么做
将 async 关键字放在 apiHandler(async function(details) {