Call Facebook Messenger API synchronously
I am using the Facebook Messenger API to create a very simple chat. I want to be able to send a series of messages in separate bubbles. However, when I call the API multiple times in the same function. I can't be sure which message will show first. How can I use async / await functions to order messages correctly?
Function call initially:
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");
}
Assistants:
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;
});
}
+3
source to share
1 answer
How about this:
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);
}
}
+3
source to share