user1907509 user1907509 - 8 days ago 6
Javascript Question

Chaining function calls using promises

Hi Im trying to call subsequent functions of the same types passing parameters as shown in the example:

The problem is that im getting random output like, Line3, Line4, Line1, Line2. Am I doing something wrong with the chaining of is it a problem with the latency of the rendering of each text to screen? Should i use npm sleep?

var function1 = (senderID,req,FB_ID) => {

return new Promise((resolve,reject) => {

var line1 = 'Line1';
var line2 = 'Line2';
var line3 = 'Line3';
var line4 = 'Line4';

// Display lines of text
sendTextMessage(senderID,line1)
.then(sendTextMessage(senderID,line2))
.then(sendTextMessage(senderID,line3))
.then(sendTextMessage(senderID,line4))
.then(resolve());
});
};


Each sendTextMessage call calls this function below:

var sendTextMessage = (recipientId, messageText) => {

return new Promise((resolve,reject) => {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};

callSendAPI(messageData).then(function(){
resolve();
});
});
};


CALLSENDAPI :

var callSendAPI = (messageData) => {
var sleepSec = 1;
return new Promise((resolve,reject) => {

request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: process.env.FB_PAGE_TOKEN },
method: 'POST',
json: messageData

}, function (error, response, body) {
if (!error && response.statusCode == 200) {
//var recipientId = body.recipient_id;
//var messageId = body.message_id;
sleep.sleep(sleepSec);
resolve();

} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
reject(error);
}
});
});

}; // func

Answer

The problem is that what you have put as then argument gets executed immediately, while instead you should pass a function.

You could use bind to avoid overly verbose anonymous functions:

sendTextMessage(senderID,line1)
      .then(sendTextMessage.bind(null, senderID,line2))
      .then(sendTextMessage.bind(null, senderID,line3))
      .then(sendTextMessage.bind(null, senderID,line4))
      .then(resolve);

Also, note the resolve at the end, without parentheses: you want to pass that function, not execute it.

Comments