我正在开发一个nodejs项目中的函数来输出数组的内容,一次一个元素。内容将输出到Facebook信使窗口,但输出之间会有一段时间延迟,以便用户有时间阅读每个短语。
输出应该按如下方式运行:
IF it is the first element
Get element text
Calculate delay based on word count
Send text (no delay for first element)
ELSE
Get next element
Send text with delay
Calculate delay for next element
REPEAT UNTIL ALL ELEMENTS SENT
此操作的代码如下所示:
sendMultipartMessage: function(recipientID, textArray)
{
let msgLength = textArray.length;
let msgDelay, msgPartCount = 0, msgTextPart;
while (msgPartCount < msgLength)
{
if (msgPartCount === 0)
{
msgTextPart = textArray[msgPartCount]; // Get the first part of the message
msgDelay = common.calculateDelay(msgTextPart);
console.log("Working with message part %s", (msgPartCount+1));
self.sendTextMessage(recipientID, msgTextPart);
}
else
{
msgTextPart = textArray[msgPartCount]; // Get the next part of the message
console.log("Working with message part %s", (msgPartCount+1));
setTimeout(function()
{
self.sendTextMessage(recipientID, msgTextPart);
}, msgDelay);
msgDelay = common.calculateDelay(msgTextPart); // Delay sending the next part to give user time to read the previous part
}
msgPartCount++;
}
},
当我运行代码时,它只输出以下内容:
MESSAGE PART 1
MESSAGE PART 4
MESSAGE PART 4
MESSAGE PART 4
有什么想法吗?
答案 0 :(得分:0)
首先:道歉,如果这篇文章中有一些错误,这是我在堆栈上的第一篇文章。
在执行第二次发送之前,看起来你的循环已完成所有元素的循环。我建议您使用promises或异步库。这样你就可以强制执行while循环等待之前的迭代。
async示例:
var async = require('async'); // don't forget to npm install the async library
/*
...
*/
sendMultipartMessage: function(recipientID, textArray){
let msgDelay = 0, msgPartCount = 0;
async.each(textArray, function(msgTextPart, callback){
console.log("Working with message part %s", (msgPartCount+1));
setTimeout(function(){
self.sendTextMessage(recipientID, msgTextPart);
}, msgDelay);
msgDelay = common.calculateDelay(msgTextPart);
callback();
}, function(error){} // final callback that contains error if something went wrong )
}
我希望这会有所帮助。
答案 1 :(得分:0)
非常感谢StackOverflow用户Explosion Pills帮助实现这一目标 - 请参阅我的另一个问题here!
我的最终解决方案如下所示:
sendMultiPartMessage: function(recipientId, textArray) {
let index = 0, msgPart, msgData;
const sendMessagePart = function(textArray, index) {
msgPart = textArray[index];
msgData = {
recipient: {
id: recipientId
},
message: {
text: msgPart
}
};
self.sendCallbackMessage(msgData, function(sent) {
index++;
if (sent && (index < textArray.length)) {
sendMessagePart(textArray, index);
}
});
};
sendMessagePart(textArray, index);
},
sendCallbackMessage: function(messageData, callback) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: config.FB_PAGE_TOKEN
},
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
let recipientId = body.recipient_id;
console.log("Message sent to recipient '%s'", recipientId);
callback(true);
} else {
console.error("Could not send message: ", response.statusCode, response.statusMessage, body.error);
callback(false);
}
}
);
},