Reputation: 109
I want to generate a random id for each user and save it in a redis set using node.js. My first approach was to generate a random id and then check it's uniqueness using redis SISMEMBER and if it wasn't unique repeat the task above using a loop. The problem is that node redis is asynchronous, So, I can't implement the loop described above. I also thought about using promises like below:
var promises = [], f=1;
while(f){
suggested_id = new_random_id();
promises.push(new Promise(function(resolve,reject) {
red_client.sismember("uids", suggested_id, function(err, value) {
if(err) {reject(err); }
resolve(value);
});
setTimeout(resolve, 1000, 'foo');
}));
Promise.all(promises).then((values)=>{
f = values[0];
});
}
}
but again Promises.all is another asynchronous function so the loop starts making innumerable calls to redis without waiting for response from the previous one. Does anyone have an idea how can this be done?
Upvotes: 0
Views: 797
Reputation: 14171
Why aren't you just waiting for the promise to finish with success and then run your job
const getUniqueId = new Promise( (resolve, reject) => {
const generateId = async () => {
suggested_id = new_random_id();
red_client.sismember("uids", suggested_id, function(err, value) {
if(err) {
// call generateId again, this is the retry
generateId ()
return
}
resolve(suggested_id);
});
})
generateId()
})
const uniqueId = await getUniqueId()
Note: considering the fact that you check for the id and later one you'll use it you risk loosing the id in the mean time.
Upvotes: 1