I am new to Javascript and having trouble understanding how to make my functions run after one another. I want to use Promise to achieve this.
I am following Facebook Messenger tutorial to make a chat bot. Basically, I want to send messages one after another.
If I call the following lines:
sendTextMessage(recipientID, "1");
sendTextMessage(recipientID, "2");
sendTextMessage(recipientID, "3");
sendTextMessage(recipientID, "4");
sendTextMessage(recipientID, "5");
I want the message "1" to be sent first. Then, "2", "3" and so on. (instead of being sent in random order, which is the problem here.)
Here are the relevant helper functions.
function sendTextMessage(recipientId, messageText) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
Here is callSendAPI function.
function callSendAPI(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) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
if (messageId) {
console.log("Successfully sent message with id %s to recipient %s",
messageId, recipientId);
} else {
console.log("Successfully called Send API for recipient %s",
recipientId);
}
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
}
I have been stuck for a while. Any help would be greatly appreciated.
I tried this, but it didn't work. =(
sendTextMessage(recipientID, "1")
.then(sendTextMessage(recipientID, "2"))
.then(sendTextMessage(recipientID, "3"));