Reputation: 540
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...
Now redis connection is getting closed before all the set operation is completed inside the for loop.
Additional detail...
Upvotes: 2
Views: 3160
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 untilMulti.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
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
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