Skip to content

Instantly share code, notes, and snippets.

@emilioriosvz
Created September 7, 2017 12:04
Show Gist options
  • Save emilioriosvz/3c1b8a6b1e3ab771ea44e35c079c9f5f to your computer and use it in GitHub Desktop.
Save emilioriosvz/3c1b8a6b1e3ab771ea44e35c079c9f5f to your computer and use it in GitHub Desktop.
rabbitmq async await
var amqp = require('amqplib')
var open = require('amqplib').connect('amqp://localhost');
const connect = (url = 'amqp://localhost') => {
return new Promise((resolve, reject) => {
amqp.connect(url)
.then(conn => resolve(conn))
.catch(err => reject(err))
})
}
const createChannel = conn => {
return new Promise((resolve, reject) => {
conn.createChannel()
.then(channel => resolve(channel))
.catch(err => reject(err))
})
}
const channelAssertQueue = (channel, queueName) => {
return new Promise((resolve, reject) => {
channel.assertQueue(queueName)
.then(asserted => resolve(channel))
.catch(err => reject(err))
})
}
const sendToQueue = (channel, queueName, buffer) => {
channel.sendToQueue(queueName, buffer)
}
const connection = async (queueName = 'msg.*') => {
var conn = await connect()
var channel = await createChannel(conn)
var assertedChannelToQueue = await channelAssertQueue(channel, queueName)
return channel
}
module.exports = connection
@emilioriosvz
Copy link
Author

Why don't use async/await in all functions, like this:

const channelAssertQueue = async (channel, queueName) => {
  try {
    await channel.assertQueue(queueName)

    return channel
  } catch (error) {
    throw error;
  }
}

Totally agreed, with async await everything is much cleaner.

@wajdijurry
Copy link

wajdijurry commented May 14, 2021

var amqp = require('amqplib/callback_api');
var config = require('../config/config');

const connect = (url) => {
    return new Promise((resolve, reject) => {
        amqp.connect(url)
            .then(conn => resolve(conn))
            .catch(err => reject(err))
    })
}

I got an error:

expressjs_1    | /app/modules/new_client.js:7
expressjs_1    |             .then(conn => resolve(conn))
expressjs_1    |             ^
expressjs_1    | 
expressjs_1    | TypeError: Cannot read property 'then' of undefined

UPDATE
I was using amqplib/callback_api library, while I should use amqplib instead.

@wajdijurry
Copy link

This is an RPC model for who still search for it
https://gist.github.com/wajdijurry/d05383809a70cd93ed403f3f440f917d

@julien-sarazin
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment