I am using Q to prevent callback hell but I have reached a part of my code that I don't know how to arrange:
I am searching for scheduled messages to be delivered. For each of them, I try to send them one by one and if it could be sent, removes it from the database. The ugly part is to have a then() inside a for loop. This way I end up having nested promises instead of nested callbacks!!!! Suggestions?
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);
}
});
}
});