Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js redis promisify with .multi or .batch

Using the npm module 'redis', I've had no problem using utils promisify for single commands.

const { promisify } = require("util");
const redis = require("redis");
const client = redis.createClient();

const hmgetAsync = promisify(client.hmget).bind(client),

Now I want to be able to use the .multi and .batch methods.

Here is an example of one of my helper functions that uses .batch without promisify and non of the promisify versions of commands.

const getData = async (ids) => {
    const batch = client.batch();

    ids.forEach(id => {
        batch.hgetall(id)
    });

    return new Promise((resolve, reject) => {
        batch.exec((err, replies) => {
            if (err) {
                reject(err);
            }

            const data = replies
                // missing keys require filtering
                .filter(it => !!it)
                .map(dataPoint => _toDataPoint(dataPoint));

            resolve(data);
        })
    })
};

Works no problem, but I'm curious if it is possible to use promisify with either .multi or .batch

Many thanks,

like image 632
Aaron Avatar asked Dec 02 '25 04:12

Aaron


1 Answers

Here is an example of promisified version of multi with an array of commands as an argument:

const { promisify } = require("util");
const redis = require("redis");
const client = redis.createClient();

const multiPromisified = commands => {
        const multi = client.multi(commands);
        return promisify(multi.exec).call(multi);
}

multiPromisified([['get', 'key1'], ['get', 'key2']]);
like image 59
Ihor Sakailiuk Avatar answered Dec 04 '25 20:12

Ihor Sakailiuk