【发布时间】:2014-12-10 13:26:39
【问题描述】:
我正在使用 Q 来防止回调地狱,但我已经到达了我不知道如何安排的部分代码:
我正在搜索要发送的预定消息。对于它们中的每一个,我尝试将它们一个一个发送,如果可以发送,则将其从数据库中删除。丑陋的部分是在 for 循环中有一个 then()。这样我最终得到了嵌套的承诺而不是嵌套的回调!!!!有什么建议吗?
appLog.debug("Looking for scheduled messages");
var messages = messageService.findScheduled()
.then(function(messages){
appLog.debug("found [%d] stored messages",messages.length);
for(var i = 0; i<messages.length; i++){
messageService.send(msg.namespace, msg.message, msg.data)
.then(function(result) {
if (result == constants.EVENT_EMIT_SENT) {
appLog.debug("Message [%s] sent!!!", msg._id);
messageService.remove(msg._id)
.then(function(result) {
appLog.debug("Message deleted: [%s]", msg._id);
})
.fail(function(err) {
appLog.error("The message couldn't be deleted: [%s]", msg._id);
});
}else if (result == constants.EVENT_EMIT_NOT_SENT_AND_NOT_STORED) {
appLog.debug("Message [%s] not sent", msg._id);
}
});
}
});
【问题讨论】:
-
一种方法是不使用
q,而是使用bluebird。q很慢。 -
我是不是错过了
let msg = messages[i]? -
@majidarif:不过,使用 bluebird 并不能解决您的代码布局问题。
标签: node.js callback promise q