【发布时间】:2017-11-15 08:57:27
【问题描述】:
大家好。
你能帮我解决 node.js 中的异步问题吗?
这个问题:
我使用 amqplib module 与 RabbitMQ 一起工作,这里有方法 consume,他从 RabbitMQ 提供消息,但该方法首先返回关于他开始的承诺 在此承诺开始后,他调用回调以从 RabbitMQ 获取数据,我不知道如何捕捉所有消息何时将发送到我的节点 js 应用程序。
更多解释,这里是我的代码和在 cmets 的最后代码,我写了我想要的:
/**
* Here my test code
*
* requirng amqp.node lib
*/
let amqp = require('amqplib')
, configConnection = { /* ..config options */ }
, queue = 'users'
, exchange = 'users.exchange'
, type = 'fanout'
/**
* declare annonymous function as async and immediately called it
*/
(async () => {
/**
* declare connection and channel with using async/await construction
* who support version node.js >= 8.5.0
*/
let conn = await amqp.connect(configConnection)
let channel = await conn.createChannel()
await channel.assertExchange(exchange, type)
let response = await channel.assertQueue(queue)
/**
* response: { queue: 'users', messageCount: 10, consumerCount: 0 }
*/
response = await channel.bindQueue(response.queue, exchange, '')
response = await channel.consume(response.queue, logMessage, {noAck: false})
/**
* {noAck: false} false for not expect an acknowledgement
*/
console.log('reading for query finish')
function logMessage(msg) {
console.log("[*] recieved: '%s'", msg.content.toString())
}
})()
/**
* output will show:
* reading for query finish
* [*] recieved: 'message content'
* [*] recieved: 'message content'
* [*] recieved: 'message content'
* ...
*
* But i'm need show message 'reading for query finish' after when
* all consumes will executed
*
* Ask: How i can do this?
*/
【问题讨论】:
标签: javascript node.js async-await rabbitmq node-amqp