0

I would like create find method in my User object. This function should returns user. But for this example it returns only the text.

But I don't know how return value for waterfall.

When I run

console.log(User.find("575578a9f95d6de1354327ef"));

I got 'undefined' in my output, but I except 'function find shoud return this value', What I should to do if I want get 'function find shoud return this value' text on my output

User = {
    collectionName: 'users',

    find: function(id){
        async.waterfall(
            [
            function(callback) {
                MongoClient.connect('mongodb://127.0.0.1:27017/lingogo', function(err,db) {
                    if(err) { throw err}
                    callback(null, db, id);

                });
            },
            function(db,id, callback) {
                var collection = db.collection(User.collectionName);
                collection.find({'_id': ObjectID(id)}).toArray(function (err, result) {

                    if (err) { throw err };

                    if (result[0] && result[0]._id != '') {
                        return callback(null,result[0]);
                    }

                    return callback(null,null);
                })
            },
            ],
            function (err, user) {

                return 'function find shoud return this value';
            }
        );
    }
}
console.log(User.find("575578a9f95d6de1354327ef"));
1
  • connect before each .find is bad idea. Commented Jun 10, 2016 at 10:08

1 Answer 1

2

Function find must have a callback too, that you call in a callback of waterfall. You cannot return a value synchronously from an asynchronous function.

find: function (id, callback) {
    async.waterfall(..., function (...) {
        callback(null, return_value);
    });
}

That should be called like

User.find("575578a9f95d6de1354327ef", function (err, return_value) {
    console.log(return_value);
});
Sign up to request clarification or add additional context in comments.

3 Comments

I try this but I got error: TypeError: undefined is not a function I you want, you can see my update. pastebin.com/qVXTpNWS
@PawełBrzoski You still call that method synchronously. Once you're into asynchronous code, there's no way out, your calls have to be asynchronous too. Take a look on updated answer.
@PawełBrzoski Though I recommend looking into more Promise-like API, because code with callbacks becomes unwieldy quite soon.

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.