我正在使用Facebook Messenger API创建一个非常基本的聊天机器人。我希望能够在单个气泡中发送一系列消息。但是,当我在同一个函数中多次调用API时。我无法确定首先会显示哪条消息。如何使用async / await功能正确排序消息?
最初的函数调用:
const getStartedProcess = async(formattedText,senderID) => {
const firstMessage = await sendTextMessage(senderID,"First message");
const secondMessage = await sendTextMessage(senderID,"Second message");
const thirdMessage = await sendTextMessage(senderID,"Third message");
}
助手:
const sendTextMessage = async(recipientId, messageText) => {
//format message correctly
const sent = await callSendAPI(messageData);
return 0;
}
const callSendAPI = async(messageData) =>{
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData
}, function (error, response, body) {
//Proccess
return 0;
});
}
答案 0 :(得分:3)
这个怎么样:
const sendTextMessage = (recipientId, messageText) => {
return new Promise((resolve, reject) => {
//format message correctly
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token: PAGE_ACCESS_TOKEN},
method: 'POST',
json: messageData
}, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(response);
}
});
})
}
const getStartedProcess = async(formattedText,senderID) => {
try {
const firstMessage = await sendTextMessage(senderID, "First message");
const secondMessage = await sendTextMessage(senderID, "Second message");
const thirdMessage = await sendTextMessage(senderID, "Third message");
} catch (error) {
console.log(error);
}
}