Meteor.method hangs on call

I have a meteor code that calls an method on the server. The server code executes an API call to the USDA and puts the resulting json set into a array list. The problem is that after the Meteor.call on the client side, it hangs.

var ndbItems = [];

if (Meteor.isClient) {
    Template.body.events({
        "submit .searchNDB" : function(event) {
            ndbItems = [];      
            var ndbsearch = event.target.text.value;
            Meteor.call('getNDB', ndbsearch);
            console.log("This doesn't show in console.");  
            return false;
        }
    });
}

if (Meteor.isServer) {
    Meteor.methods({
        'getNDB' : function(searchNDB) {
            this.unblock();
            var ndbresult = HTTP.call("GET", "http://api.nal.usda.gov/ndb/search/",
                {params: {api_key: "KEY", format: "json", q: searchNDB}});
            var ndbJSON = JSON.parse(ndbresult.content);
            var ndbItem = ndbJSON.list.item;
            for (var i in ndbItem) {
                var tempObj = {};
                tempObj['ndbno'] = ndbItem[i].ndbno;
                tempObj['name'] = ndbItem[i].name;
                tempObj['group'] = ndbItem[i].group;
                ndbItems.push(tempObj);
            }
            console.log(ndbItems); //This shows in console.
            console.log("This also shows in console.");
        }
   });
}

After the call to the server and the API returns data to the console and writes it to the array, it doesn't process the console.log on the client side 1 line below the method call. How can I fix this?

Upvotes: 0

Views: 308

Answers (1)

Christian Fritz
Christian Fritz

Reputation: 21354

You forgot to give your client side call a callback function. Method calls on the client are async, because there are no fibers on the client. Use this:

if (Meteor.isClient) {
    Template.body.events({
        "submit .searchNDB" : function(event) {
            ndbItems = [];      
            var ndbsearch = event.target.text.value;
            Meteor.call('getNDB', ndbsearch, function(err, result) {
                console.log("This will show in console once the call comes back.");  
            });
            return false;
        }
    });
}

EDIT:

You must also call return on the server:

if (Meteor.isServer) {
    Meteor.methods({
        'getNDB' : function(searchNDB) {
            this.unblock();
            var ndbresult = HTTP.call("GET", "http://api.nal.usda.gov/ndb/search/",
                {params: {api_key: "KEY", format: "json", q: searchNDB}});
            ....
            console.log("This also shows in console.");
            return;
        }
   });
}

Upvotes: 1

Related Questions