You cannot return from within the callback. Do it like this:
var redis = require("redis"), client = redis.createClient(); function generatePageUrl(cb) { var randomStr = randomInt.toString(32); // Check whether this URL is already in our database; client.smembers("url:" + randomStr, function (err, data ) { if (data.length != 0) { // URL already in use, try again getPageUrl(cb); } cb(randomStr); }); } generatePageUrl(function(page_url){ // add it to the database, etc });
If you don't like this style, you can consider streamlinejs - it allows you to write your code like this
var redis = require("redis"), client = redis.createClient(); function generatePageUrl(_) { var randomStr = randomInt.toString(32); // Check whether this URL is already in our database; var data = client.smembers("url:" + randomStr, _); if (data.length != 0) { // URL already in use, try again return getPageUrl(_); } return randomStr; } var page_url = generatePageUrl(_); // add it to the database, etc
thejh source share