Created
September 7, 2017 12:04
-
-
Save emilioriosvz/3c1b8a6b1e3ab771ea44e35c079c9f5f to your computer and use it in GitHub Desktop.
rabbitmq async await
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
In line 3 recall of require('amqplib')
thanks...helpfully.
awesome
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;
}
}
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.
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.
This is an RPC model for who still search for it
https://gist.github.com/wajdijurry/d05383809a70cd93ed403f3f440f917d
typescript version
https://gist.github.com/julien-sarazin/f884f28a2d59f37ff22227f64ff7f2a5
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
brilliant )