Search code examples
javascriptmeteormeteor-helper

Meteor.call() with return value while server have async work


I'm working with Meteor and I'm trying to retrieve data from an external database (neo4j for that case).

My problem is when I Meteor.call() from the client to the server I need to have a return statement in the server function. But retrieving data from the database is async by itself.

This is a snippest of what I have:

client.js:

Template.test.created = function () {
    Meteor.call('getData', id, function (error, response) {
        if (response) {
            console.log(response); //<-- reponse = "???"
        }
    });
}

server.js:

Meteor.methods({
    "getData": function (id) {
        neo.commit ( //<-- async function which expect a callback
            id,
            function(error, response) {
                console.log(response); //<-- only here I have the response I want but now I cant "return" it.
                return response;
            }
        );
        return "???"; //<-- the actual return that is being send back
    }
});    

Any ideas?


Solution

  • You can use Future to fix your problem, Change your code to(it may need more changes depending on your code base):

    ...
    
    var Future = Npm.require('fibers/future');
    
    Meteor.methods({
        "getData": function (id) {
            var future = new Future();
            neo.commit ( //<-- async function which expect a callback
                id,
                function(error, response) {
                    if (error) return future.throw(error);
                    return future.return(response);
                }
            );
            return future.wait();
        }
    });
    

    You can read more about Meteor's async patterns in the following links:

    Async On Meteor Server

    Meteor Async Guide

    Meteor Patterns: Call an asynchronous function and use its returned value

    Feel free to ask if you need further helps.