简体   繁体   中英

Meteor: visible on console (server), sends undefined to client

Finally diving into meteor. I have a small problem regarding http get requests.

On the client a simple call is executed to get data from the server.

if (Meteor.isClient) {
Template.liveprice.helpers({
    price: function() {
        Meteor.call('getPrice', function(error, response) {
            if (error) {
                return error;
            } else {
                return response;
            }
        })
    }
})
}

On the server data is retrieved from a live and public API. It works fine on the server, but an undefined result is send back to the client. What am I missing here?

if (Meteor.isServer) {
Meteor.methods({
    getPrice: function() {
        var url = 'https://www.bitstamp.net/api/ticker/';
        var req = HTTP.call('GET',url,function(error, result) {
            //console.log(result);
            if (result.statusCode == 200) {
                var last = result.data.last;
                console.log(last);//this shows the desired result in the server's console
                return last;//sends back undefined to the client
            } else {
                return error;
            }
        });
    }
})
}

@epascarello is right. Luckily, Meteor's HTTP works synchronously as well thanks to fibers. Try this:

Meteor.methods({
    getPrice: function() {
        var url = 'https://www.bitstamp.net/api/ticker/';
        var result;

        try {
          result = HTTP.get(url);
          check(result.data.last, String);
          return result.data.last;
        } catch (error) {
          throw new Meteor.Error('get-price-failed', 'Could not retrieve the price.');
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM