2016-11-26 54 views
-1

您好林試圖調用傳遞參數的相同類型的後續函數如示例所示:鏈接函數調用使用許諾

的問題是,即時得到隨機的輸出等,3號線,線路4,線路1,線路2。我是否在鏈接上做錯了是每個文本渲染到屏幕的延遲問題?我應該使用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 
+0

我可以建議,在'sendTextMessage'中,刪除整個Promise構造函數,並簡單地返回'callSendAPI(messageData)' –

回答

5

的問題是,你已經把爲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); 

而且,請注意resolve末,沒有括號:要該功能,不執行它。