使用promises链接函数调用

时间:2016-11-26 19:50:24

标签: javascript node.js promise

您好我试图调用相同类型的后续函数传递参数,如示例所示:

问题是即时获取随机输出,如Line3,Line4,Line1,Line2。我是否做错了链接是否是每个文本呈现到屏幕的延迟问题?我应该使用npm睡眠吗?

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

每个sendTextMessage调用都会调用以下函数:

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

1 个答案:

答案 0 :(得分:5)

问题是你作为O(N log N)参数放置的内容会立即被执行,而你应该传递一个函数。

您可以使用then来避免过于冗长的匿名函数:

bind

另外,请注意最后的sendTextMessage(senderID,line1) .then(sendTextMessage.bind(null, senderID,line2)) .then(sendTextMessage.bind(null, senderID,line3)) .then(sendTextMessage.bind(null, senderID,line4)) .then(resolve); ,没有括号:您希望传递该功能,而不是执行