manbearpig1 manbearpig1 - 2 months ago 8
Javascript Question

How to get value back using callback

I receive an id. I relay the id to my function findById() which is located in post.js and it's job is to find the user who wrote the post with the id it's given.

app.js

socket.on('postId', function(data) {
post.findById(data);
});


post.js

// Find post by its Id.
exports.findById = function(data) {
console.log('data at export was: ' + data);
var cursor = postsCollection.find({"_id" : ObjectId(data)}).toArray(function(err, record) {
if(err)
throw err;
// Got the name of roomCreator.
console.log(record[0].username);
});
}


I successfully log the data that I want. I need the data from post.js returned back to app.js. I can't simply return the value in post.js and set the function call in app.js equal to a variable, this isn't working. How can I get the value from post.js back for use in app.js?

Answer

try this

    socket.on('postId', function(data) {
      post.findById(data, function(username) {
        console.log(username);
      });
    });

    // Find post by its Id.
    exports.findById = function(data, callback) {
        console.log('data at export was: ' + data);
        var cursor = postsCollection.find({"_id" : ObjectId(data)}).toArray(function(err, record) {
            if(err)
                throw err;
            // Got the name of roomCreator.
            console.log(record[0].username);
            return callback(record[0].username);
        });
    }
Comments