In the following code, I have an infinite loop which I don't know why it happens. My best guess is because the function inside is async
the loop doesn't wait for it and so the loop never stops. What is the best way to solve this issue ?
var generateToken = function(userId) {
return new Promise(function(resolve, reject) {
User.findOne({userId: userId}, function(err, user) {
if (user !== null) {
var loop = true;
while (loop) {
var token = Common.randomGenerator(20);
(function(e) {
User.find({tokens: e}, function(err, result) {
if (err) {
loop = false;
reject('Error querying the database');
} else {
if (result.length === 0) {
if (user.tokens === undefined) {
user.tokens = [];
}
user.tokens.push(e);
loop = false;
resolve();
}
}
});
})(token);
}
} else {
return reject('UserNotFound');
}
});
});
};
This function receives a userId (User.findOne()
is used to find the user and if there's no user with that id , reject the promise) and creates a unique random token for that user (randomGenerator
) , add it to the user entity which is kept in MongoDB and the return it back to the caller.
(NOTE There were some down votes saying this question is same as this one Which is not as I already had a closure in my code and it still doesn't work. That question was more about how to bind the looping variable to the closure)