JavaScript flow control in node / redis: returning from internal callback?

New question. Why does this JavaScript function return undefined?

var redis = require("redis"), client = redis.createClient(); function generatePageUrl() { 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 return getPageUrl(); } return randomStr; }); } var page_url = generatePageUrl(); // add it to the database, etc 

I assume that he must be to the end and return before he reaches inside client.smembers .

But I really need to check the contents of the Redis set before returning it: can I make it return from within the callback? If not, what can I do?

In addition, advice on how I used this function recursively would be glad - I'm not sure if this is entirely reasonable :)

Thanks for the help to the beginner.

+4
source share
1 answer

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 
+2
source

All Articles