最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在发送消息之前执行查询

运维笔记admin9浏览0评论

在发送消息之前执行查询

在发送消息之前执行查询

我在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&timesel=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&timesel=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;)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论