Search code examples
javascriptnode.jsfacebookasync-awaitmessenger

Calling Facebook Messenger API in a synchronous fashion


I'm using the Facebook Messenger API to create a very basic chatbot. I want to be able to send a series of messages in individual 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 functionality to correctly order the messages?

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");
}

Helpers:

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;
  });
}

Solution

  • 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);
        }
    }