0

I am writing a callback function in node.js but it is returning me an undefined value. Below is the code

exports.getRecord = (function(callback) {
    return function(req, res) {
        var recordName;
        DBObject.record.find(jsonString, function(err, doc_record) {
            doc_record.forEach(function(docRecordTravel) {
                recordName = callback(docRecordTravel.recordCode);
                console.log(recordName);
            })
            }
    })(callbackFunc);

    function callbackFunc(recordCode) {
        var recordName;
        DBObject.var_recordRack.find({
            recordID: recordCode
        }, function(err, record) {
            record.forEach(function(recordLoop) {
                recordName = recordLoop.recordName;

            });
            console.log("callback " + recordName);
            return recordName
        });
    }

In callbackFunc it is showing me the recordName but when i return it it displays undefined. how can I return the value in call backs in node.js.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
JN_newbie
  • 5,492
  • 14
  • 59
  • 97
  • Take a look at [this question](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call). Don't let the AJAX angle throw you off: the issues are the same. – Louis Jan 06 '14 at 15:30

1 Answers1

1

You can't.

It uses a callback function because it is asynchronous.

By the time the callback is called, the previous function has already finished and there is nowhere to return the value to.

If you want to do something with the data, then you must do it from the callback function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335