【问题标题】:amqp callback confirm: true not workingamqp 回调确认:真的不工作
【发布时间】:2017-06-12 01:45:42
【问题描述】:

我是 NodeJS 的新手,我们使用的是 amqp 0.2.6。我有看起来像的伪代码

async.waterfall([
    function(callback) {
         // do logic and pass parameters to next method by calling callback
    },

    function(params, callback) {
         // do AMQP logic and pass parameters to next method
            try {       
          bus.publish(routingKey, message, options, function (err) {
                 console.log("got here");
                 if (err) {
                      console.log(err);
                 }
          });
        //callback(null, null);    
    } catch (err) {
        console.log("ERROR: " + err);
        //callback(err, null);
    }


    }
], function() {
        // do logic with all results
});

所以我有几个问题。首先,当我调用发布时,我的回调有问题吗?我的消息被正确发送给兔子,但我从来没有收到回调got here 消息。

如果我取消注释以回调开头的两行,那么我在 async.waterfall 中的第二个函数会立即获取它的回调,然后调用它的回调将结果传递给 async.waterfall 中的最终函数。我明白这是因为回调在发布后立即被调用。我想要做的是理想情况下在我知道我发送给兔子的消息是否成功且没有错误或有错误之后调用回调。我不知道该怎么做,因为我无法访问 amqp 发布消息的回调。如果有错误,我确实在我的 try/catch 块中看到,我看到我的错误已记录,但这是在我的 async.waterfall 函数已经完成之后。我想将发布消息的结果(成功或失败)传递给 async.waterfall 中的第二个函数。我可以实现的任何非阻塞方式都可以。所以最终的目标是

async.waterfall([
    function (one) {
         // do logic and pass results to 'two'
    }, 
    function (two) {
         // do AMQP logic, send a message, get the results of that action and pass to last function
    }
], function() {
        // i got my results from 'one' and 'two', do some more logic
});

【问题讨论】:

    标签: javascript node.js asynchronous callback


    【解决方案1】:

    您可以简单地将瀑布回调作为bus.publish() 回调传递。这将在 bus.publish() 完成时调用该回调,并且您在 async.waterfall() 中的最终函数将出现错误(如果传递了错误)和/或来自 bus.publish() 的结果。

    更新后的代码示例可能如下所示,但您可以对其进行调整以满足您的需求。

    async.waterfall([
        function(callback) {
             // do logic and pass parameters to next method by calling callback
             callback(null, params)
        },
    
        function(params, callback) {
             // do AMQP logic and pass parameters to next method    
             bus.publish(routingKey, message, options, callback)
        }
    ], function(err, result) {
            // err:    if an error is thrown and passed into the callback for bus.publish(), should be set here, otherwise should be `null` 
            // result: if bus.publish() gives you a result in the callback after it publishes the message, would be here
    })
    

    【讨论】:

    • 是的,这不起作用,因为就像我提到的那样,由于某种原因没有调用 publish() 中的回调。
    • 好的,那就是具体发布方式的问题了。您可以提供发布方法的代码,还是使用特定的库?如果它是一个库,并且您确信您已经为方法提供了它需要按预期工作的参数,那么您可能应该向维护者提出问题,因为您的问题不在于异步库或你正在使用的模式。即便如此,您仍应确保在发布方法中调用回调,以确保在那里捕获错误。
    • 查看文档 (npmjs.com/package/…) 似乎只有在交换处于“确认模式”时才会调用回调。你确认了吗?
    • 我确实设置了该属性,并在我的代码中检查了交换机上的 confirm 属性是否设置为 true。所以我真的不确定为什么没有调用该回调。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    • 2014-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多