我正在用NodeJS制作Messenger机器人。我希望用户能够请求所有火车。问题是我们要在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('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')
.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": "https://graph.facebook.com/v2.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上的用户。
答案 0 :(得分:0)
将callSendAPI()
放入Axios回调
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('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')
.then(function(response) {
// handle success
data = data.response;
})
response = {
"text": data.connections.arrival.name
}
callSendAPI(sender_psid, response);
break;
}
}
答案 1 :(得分:0)
您的代码中存在一些不必要的变量和问题(例如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
看起来像是超级代理;)