0

This my code. Please help me. Return budget from callbacks how value main function.

How return value main function

    //Метод возвращает текущий бюджет пользователя
    getCurrentBudget: function (req) {
        var reqToken = req.headers["authorization"].substr(7);
        var is = true;

        jwt.verify(reqToken, config['jwt'], function (error, user) {
            // Если бюджет текущего пользователя
            if (user.currentBudget) {
                db.budget.findOne({ownerId: objectId(user._id)}, function(error, budget) {
                    if (!error && budget) {
                        //Бюджет найден
                        logger.debug('Бюджет найден: %j', budget, {});
                        return budget;
                    }
                })
            } else {
                // Ищем бюджет в который пригласили этого пользователя
                db.budget.findOne({membersEmail: user.email}, function(error, budget) {
                    if (!error && budget) {
                        //Бюджет найден
                        logger.debug('Бюджет найден: %j', budget, {});
                        return budget;
                    }
                })
            }
        });
    },
Maksim Borodov
  • 419
  • 2
  • 7
  • 13
  • `getCurrentBudget()` should be declared as `var getCurrentBudget = function(){...};` for starters. – JayRow May 07 '14 at 22:48
  • Impossible. The main function exists long before the callback is invoked. Do a search and you'll find hundreds of other questions asking how to return a value from a callback or from an AJAX request. The solutions there will be helpful. Basically you don't return the data to the code, you bring to code to the data. – cookie monster May 07 '14 at 22:48
  • You could also use a promise framework/library (such as q, see https://github.com/kriskowal/q), to make the code more robust. Either way, you need to use callback functions as suggested in the answers below, since you are dealing with asynchronous JavaScript here. – Genti Saliu May 07 '14 at 22:55

2 Answers2

1

Because you call asynchronous code from your function you need to provide callback to "return" result. For example:

getCurrentBudget: function (req, callback) {
    var reqToken = req.headers["authorization"].substr(7);
    var is = true;

    jwt.verify(reqToken, config['jwt'], function (error, user) {
        // Если бюджет текущего пользователя
        if (user.currentBudget) {
            db.budget.findOne({ownerId: objectId(user._id)}, function(error, budget) {
                if (!error && budget) {
                    //Бюджет найден
                    logger.debug('Бюджет найден: %j', budget, {});
                    callback(budget);
                }
            })
        } else {
            // Ищем бюджет в который пригласили этого пользователя
            db.budget.findOne({membersEmail: user.email}, function(error, budget) {
                if (!error && budget) {
                    //Бюджет найден
                    logger.debug('Бюджет найден: %j', budget, {});
                    callback(budget);
                }
            })
        }
    });
},
Ivan Nevostruev
  • 28,143
  • 8
  • 66
  • 82
0

Try this:

getCurrentBudget: function (req, callback) { // callback is a function to get budget
    var reqToken = req.headers["authorization"].substr(7);
    var is = true;

    jwt.verify(reqToken, config['jwt'], function (error, user) {
        // Если бюджет текущего пользователя
        if (user.currentBudget) {
            db.budget.findOne({ownerId: objectId(user._id)}, function(error, budget) {
                if (!error && budget) {
                    //Бюджет найден
                    logger.debug('Бюджет найден: %j', budget, {});
                    callback(budget);
                }
            })
        } else {
            // Ищем бюджет в который пригласили этого пользователя
            db.budget.findOne({membersEmail: user.email}, function(error, budget) {
                if (!error && budget) {
                    //Бюджет найден
                    logger.debug('Бюджет найден: %j', budget, {});
                    callback(budget);
                }
            })
        }
    });
}

And in your main, you call this method like this:

main function() {

  getCurrentBudget(req, function(budget) { // this function is your callback actually
     console.log(budget);
  });
}
Cute_Ninja
  • 4,742
  • 4
  • 39
  • 63