anish
anish

Reputation: 7412

How to return data from the callback nodejs

How to return from the inner callback, in the below scenario, a json data is being return, when i try to do console.log it print the [Function] instead of json value

exports.tests = function(tagName, out) {

    model.findbyTag(tagName, function(data) {

        var json = {
            "name" : 'java',
            "data" : "SomeData"
        }

        return json;

    });

}

console.log(this.tests)

it output

[Function]

What wrong i'm doing so that when this method execute it should return the json data

Upvotes: 1

Views: 9293

Answers (3)

George Mylonas
George Mylonas

Reputation: 722

You need to use Node emitter for that, if you use Node in the first place of course.

const EventEmitter = require('events');

class MyEmitter extends EventEmitter {}

const myEmitter = new MyEmitter();
myEmitter.on('event', (someProps) => {
  console.log('an event occurred!');
});
myEmitter.emit('event', {...someProps});

Then you can access the json and call any further actions that is required. Working with events might make you to restructure your application slightly. https://nodejs.org/docs/latest/api/events.html#events_emitter_on_eventname_listener

Upvotes: -1

Elyas74
Elyas74

Reputation: 548

module.exports = function() {

    var _return  = {};

    _return.someName = function(tagName ,callback){
        model.findbyTag(tagName, function(err ,data) {
            var json = {
                "name" : 'java',
                "data" : "SomeData"
            }
            callback(json);
        });
    }

    return _return ;
}

You can use above code like this in another file :

var sample_file = require('above code file address');

sample_file.someName(someTagName , function (data) {
    console.log(data) // this data is the json data
})

Upvotes: 3

Nunners
Nunners

Reputation: 3047

You can't return data from a callback, instead you should pass a function into the method that can be called inside the callback with the result.

Example :

exports.tests = function(tagName, out, returnFunction) {

    model.findbyTag(tagName, function(data) {

        var json = {
            "name" : 'java',
            "data" : "SomeData"
        }
        // Call the returnFunction instead of trying to return data
        returnFunction(json);

    });

}

And then call it as so :

this.tests('tagName', 'out', function(r) {
    // Where "r" is the result of the callback
    console.log(r);
});

Upvotes: 1

Related Questions