user1907509 user1907509 - 1 year ago 76
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

Each sendTextMessage call calls this function below:

var sendTextMessage = (recipientId, messageText) => {

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



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

uri: '',
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;

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

}; // func

Answer Source

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:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download