Skip to content

Instantly share code, notes, and snippets.

@barodeur
Created April 26, 2015 05:49
Show Gist options
  • Save barodeur/475fc14953acd0a398ff to your computer and use it in GitHub Desktop.
Save barodeur/475fc14953acd0a398ff to your computer and use it in GitHub Desktop.
unique token generation example
// mock for collection.findOne
// the fourth call returns true the fifth returs false
var i = 0;
var isTokenInDB = function(token, callback) {
setTimeout(function() {
callback(null, (++i) < 5);
}, 200);
};
// generate random string
var genToken = function() {
return "" + Math.random();
};
// generate a unique token in the database
var genUniqueToken = function(cb) {
var token = genToken();
isTokenInDB(token, function(err, result) {
if(result) {
console.log(' ', token)
genUniqueToken(cb);
} else {
cb(null, token);
}
});
};
// Usage
genUniqueToken(function(err, uniqueToken) {
console.log('---> ' + uniqueToken);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment