Shashank Sachan
Shashank Sachan

Reputation: 540

Async redis & promise

I have a scenario where I have to run a loop and each iteration call redis set function (async) and then I have to close the connection to redis.

Sequence...

  1. Run the foreach loop.
  2. For each element use the redis set command.
  3. When loop is completed, close the redis connection.

Now redis connection is getting closed before all the set operation is completed inside the for loop.


Additional detail...

Upvotes: 2

Views: 3160

Answers (3)

scniro
scniro

Reputation: 16989

You don't need to hack around structure - the node.js client supports techniques to do this out of the box. Check out Multi.exec

Commands are queued up inside the Multi object until Multi.exec()

// iterate and construct array of set commands
let commands = items.map(i => ['set', i.key, i.value]);

client
  .multi(commands)
  .exec((err, replies) => {
    // disconnect here
  });

If you don't actually need the transactions, you can batch all your commands at once via client.batch. You then of course can organize your connect and disconnect strategy around this pattern accordingly.

Upvotes: 3

Jerry Chen
Jerry Chen

Reputation: 715

First you create a array of promise and then use Promise.all eg:

function connectPromise (paramers) {
  return new Promise((resolve, reject) => {
    // if connectToRedisAndSetFunc is a promise
    // conectToRedisAndSetFunc(params).then(data => {
    //  resolve(data)
    //}).catch(err => {
    //  reject(err)
    // })
    conectToRedisAndSetFunc(params, function(err, data) {
      if (err) {
       reject(err)
      } else {
       resolve(data)
      }
    })
  })
}
// create promiseArray
let connectsPromises = params-array.map(p => connectPromise(p))

Promise.All(connectsPromises).then(data => {
  // close redis here
}).catch(err => {
  console.log(err)
})

Upvotes: -1

Asim
Asim

Reputation: 1490

You can use asyncLoop for this type of problem, it helped me a lot in similar circumstances:-

var asyncLoop = require('node-async-loop');
asyncLoop(arr, function (item, next){
  // foreach loop on the array "arr"
  //the each element is "item"
  //call next when the iteration is done

 //execute redis command on "item" and then do
 next();

}, function(err)
  if(err==null)
{
//do something on loop complete like closing connection etc
});

This is the basic way in which you can do what you want, you can isntall async loop likes this:-

npm install --save node-async-loop

Upvotes: 0

Related Questions