Friday 14 July 2017

Async / Await and callbacks

Hi everyone,I'm trying to set up a simple async function that awaits messages from rabbit mq and then processes them. I'm having some trouble though. Below is an example.// listener.jsconst amqp = require('amqplib') async function newMsg(){ try{ const connection = await amqp.connect(${addresss}) const channel = await connection.createChannel() channel.assertQueue('queueName', msg => { let msgBody = JSON.parse(msg.content.toString()) channel.ack(msg) return msgBody }) }catch(e){ throw new Error(e) } } module.exports = newMsg I then have a seperate module consuming these messages and processing them;// someService.jsconst newMsg = require('./listener') async function listen(){ try{ let scrapeRequest = await newMsg() // ... do things with the message }catch(e){ console.warn(e) } listen() } Running someService.js doesn't seem to wait on a msg being produced. If newMsg() only returns once the channel.assertQueue callback fires, and newMsg being an async function means it returns as a promise, why is the code running to completion early?Are there any good examples of async / await with a message queue? It seems tricky to structure, especially if I try to ack messages outside of the inital newMsg function.

Submitted July 14, 2017 at 08:19AM by ajc820

No comments:

Post a Comment