Created
April 26, 2015 05:49
-
-
Save barodeur/475fc14953acd0a398ff to your computer and use it in GitHub Desktop.
unique token generation example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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