1

all. I'm using asyncjs's waterflow method to return res value at last.But following code is return undefined value.

var async = require("async");
User.findBy = function(name,password){
  async.waterfall([
      function fetch(callback){
        db.lrange("users",0,-1,function(err,users){
          users.forEach(function(item){
            var u = JSON.parse(item);
            if ((u.name == name) && (u.password == password)){
              console.log(u);
              callback(null,u);
              return;
            }
          });
        });
        callback(null);
      }
      ],function end(err,res){

        setTimeout(function(){
        // I want to return res value at last.
        return u;
        },0);
      });
};

app.js

 // but it returns undefined value.
 var user = User.findBy("nobinobiru",a");

Do you have any idea? Please any help. Thanks in advance.

3
  • 1
    I don't know asyncjs, but it sounds like you're trying to get the result synchronously (that's what var user = and return imply). Is that what you're trying to do? Commented Aug 4, 2012 at 11:44
  • 1
    The User.findBy doesn't have return statement so its return value is undefined. Make it take a callback and call that. Commented Aug 4, 2012 at 11:48
  • You can't do what you're trying to do the way you're trying to do it. Also, using "waterfall" when you've just got one function to call seems unnecessary. Commented Aug 4, 2012 at 11:50

1 Answer 1

1

In fetch function you calling callback(null); immediately after the db.lrange call. This call unnecessary here, because you need to wait results from db.

This code should work fine:

var async = require("async");
User.findBy = function(name,password){
    async.waterfall([
        function fetch(callback){
            db.lrange("users",0,-1,function(err,users){
                var user;
                if (users && users.length) {
                    users.forEach(function(item){
                        var u = JSON.parse(item);
                        if ((u.name == name) && (u.password == password)){
                            console.log(u);
                            user = u;
                            return;
                        }
                    });
                    callback(null,user);
                } else {
                    callback(null);
                }
            });
        }
    ],function end(err,res){

        setTimeout(function(){
            // I want to return res value at last.
            return res;
        },0);
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.