Reputation: 593
I have a Redis server into AWS ElastiCache. Publishing message into the Redis channel. And trying to get the message by subscribing. I am using Javascript sample like below.
const redis = require("redis");
const subscriber = redis.createClient();
let messageCount = 0;
subscriber.on("message", function(channel, message) {
messageCount += 1;
console.log("Subscriber received message in channel '" + channel + "': " + message);
if (messageCount === 2) {
subscriber.unsubscribe();
subscriber.quit();
}
});
subscriber.subscribe("my_channel");
So far I understand as a JS novice, above sample is a synchronous call.
Now I would like to make the subscriber message call as asynchronous may be like below:
await subscriber.onAsync('message').then(function(channel, message){
console.log(JSON.stringify(message));
}).catch(function(e){
console.log(e);
});
Basically I am going to use this asynchronous call into AWS Lambda.
I am Googling continuously, but still no luck. If there is any similar Q/A, please share me.
Thanks.
Upvotes: 1
Views: 1195
Reputation: 593
I have fixed my issue by creating a function to get message from Redis channel and call the function as asynchronous. Let me share the code if it help others.
Here is the function
function getMessage(client) {
return new Promise(function(resolve) {
client.on('message', function(channel, message) {
resolve(message);
});
});
}
Here the calling part after channel subscription.
// Subscribe channel
client.subscribe('my_channel');
console.log("Subscribed");
// Get feed message from channel
feedMsg = await getMessage(client);
console.log("Message received");
Thanks.
Upvotes: 1