Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active December 9, 2022 03:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daliborgogic/37bcf51756cbd60190519c5c4394311e to your computer and use it in GitHub Desktop.
Save daliborgogic/37bcf51756cbd60190519c5c4394311e to your computer and use it in GitHub Desktop.
amqp async/await node.js
const amqp = require('amqplib')
const eventEmitter = require('events')
class OopsEmitter extends eventEmitter {}
const oopsEmitter = new OopsEmitter()
;(async () => {
try {
const conn = await amqp.connect('amqp://localhost?heartbeat=5s')
const ch = await conn.createChannel()
const queueName = 'oops.*'
const msg = 'ping ' + new Date
await ch.assertQueue(queueName, { durable: false })
// Publish
await ch.sendToQueue(queueName, Buffer.from(msg, 'utf8'))
console.log('[x] Sent %s', msg)
// Subscribe
await ch.consume(queueName, msg => {
if (msg !== null) {
oopsEmitter.emit('event', msg.content.toString())
ch.ack(msg)
}
})
await ch.close()
await conn.close()
} catch (error) {
console.error(error)
}
})()
oopsEmitter.on('event', x => {
console.log('A ', process.hrtime.bigint())
function cb () {
console.log('B ' , process.hrtime.bigint())
}
process.nextTick(cb)
setImmediate(() => console.log('C ', process.hrtime.bigint()))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment