如何优化这个Node.js + q代码以防止回调地狱? [英] How to optimize this Node.js + q code to prevent callback hell?

查看:182
本文介绍了如何优化这个Node.js + q代码以防止回调地狱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Q 防止回调地狱,但我已达到我的代码的一部分,我不知道如何安排:

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:

我正在搜索要发送的计划消息。对于他们中的每一个,我尝试一个接一个地发送它们,如果它可以发送,从数据库中删除它。丑陋的部分是在for循环中有 then()。这样我最终有嵌套的promises而不是嵌套的回调!建议?

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

        });
    }
});


推荐答案


在for循环中有一个then()。

The ugly part is to have a then() inside a for loop

不,这可能发生。虽然promise的函数式编程风格通常会导致使用 .map()和回调:-)循环是一个控制结构,并且 require 嵌套(除非您使用控制流程的例外,即分支)。

No, that can happen. Though the functional programming style of promises usually leads to using .map() with a callback anyway :-) Looping is a control structure, and does require nesting (except you use exceptions for control flow, i.e. branching). What you don't have to do is to nest promises in promise callbacks, though.

我可以简化你的循环体到

I'd simplify your loop body to

function sendAndDelete(msg) {
    return messageService.send(msg.namespace, msg.message, msg.data)
    .then(function(result) {
        if (result == constants.EVENT_EMIT_SENT) {
            appLog.debug("Message [%s] sent!!!", msg._id);
            return msg._id;
        } else if (result == constants.EVENT_EMIT_NOT_SENT_AND_NOT_STORED) {
            appLog.debug("Message [%s] not sent", msg._id);
            throw new Error("Message not sent");
        }
    })
    .then(messageService.remove)
    .then(function(result) {
         appLog.debug("Message deleted: [%s]", msg._id);
    }, function(err) {
         appLog.error("The message has not been deleted: [%s]", msg._id);
    });
}

现在您可以执行

messageService.findScheduled()
.then(function(messages){
    appLog.debug("found [%d] stored messages",messages.length);
    return Q.all(messages.map(sendAndDelete));
})
.then(function() {
    appLog.debug("all messages done");
});

这篇关于如何优化这个Node.js + q代码以防止回调地狱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆