在发送消息之前执行查询
我在NodeJS中制作一个Messenger bot。我希望用户能够要求他们所有的火车。问题是我们想在NodeJS向用户发送消息之前执行查询。
我搜索了异步函数
function handlePostback(sender_psid, received_postback) {
let response;
// Get the payload for the postback
let payload = received_postback.payload;
// Set the response based on the postback payload
switch(payload){
case "yes" :
let data = null
axios.get('/?from=Mechelen&to=Puurs&date=010219&time=1650×el=departure&format=json&lang=en&fast=false&typeOfTransport=trains&alerts=false&resul1=1')
.then(function (response) {
// handle success
data = data.response;
})
response = {
"text": data.connections.arrival.name
}
break;
}
callSendAPI(sender_psid, response);
}
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
// Send the HTTP request to the Messenger Platform
request({
"uri": ".6/me/messages",
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
正如您所看到的,在执行查询之前,脚本已经将消息发送给Messenger上的用户。
回答如下:你的代码中有一些不必要的变量和问题(例如data = data.response
应该是data = response.data
),这将是一个带有async / await和arrow函数的现代版本。在这种情况下,您不需要回调函数,在AJAX请求之后将调用callSendAPI。我也删除了switch
,因为一个简单的if
就足够了:
const handlePostback = async (sender_psid, received_postback) => {
// Get the payload for the postback
const payload = received_postback.payload;
// Set the response based on the postback payload
if (payload === 'yes') {
try {
const response = await axios.get('http://api.irail.be/connections/?from=Mechelen&to=Puurs&date=010219&time=1650×el=departure&format=json&lang=en&fast=false&typeOfTransport=trains&alerts=false&resul1=1');
callSendAPI(sender_psid, {
'text': response.data.connections.arrival.name
});
} catch (err) {
console.log(err);
}
}
};
旁注:假设您也使用superagent,我不会使用2种不同的方式来进行http请求?因为http.request
可能与Node.js,但request
看起来像superagent;)