【问题标题】:How to return from remote API call in Meteor Method?如何从 Meteor 方法中的远程 API 调用返回?
【发布时间】:2016-12-01 21:50:15
【问题描述】:

我从流星方法调用 API。如何将数据返回给客户端?我没有成功,如下所示:

Meteor.methods({
    'geCoordinates': function(distance,location) {
        this.unblock();
        geocoder.geocode(location, function ( err, data ) {
            if (err) {
                console.log("See on error " + err)
             } else {
                lat = data.results[0].geometry.location.lat 
                lng = data.results[0].geometry.location.lng
            }
                url = 'http://localhost:3005/events?lat='+lat+'&lng='+lng+'&distance='+distance+'&sort=venue&accessToken=1048427405248222|u4dBjiRw-9gdsgml1puWYFGrEvw'
        })
    return url
    }
})

【问题讨论】:

标签: javascript meteor


【解决方案1】:

还有另一种方法可以通过使用 Promise 的良好语法来实现这一点。似乎没有多少人知道 Meteor 方法可以很好地与 Promise 配合使用。操作方法如下:

Meteor.methods({
  'geCoordinates': function(distance, location) {
    return geocoder.geocode(location).then((data) => {
      lat = data.results[0].geometry.location.lat;
      lng = data.results[0].geometry.location.lng;
      return 'http://localhost:3005/events?lat=' + lat + '&lng=' + lng + '&distance=' + distance + '&sort=venue&accessToken=1048427405248222|u4dBjiRw-9gdsgml1puWYFGrEvw';
    }).catch((err) => {
      console.log("See on error " + err);
      throw err;
    });
  }
})

【讨论】:

    【解决方案2】:

    你可以使用 Npm future 同步返回数据,使用 Npm 你的代码会是这样的

    在服务器端

    var future = require('future');
    
    Meteor.methods({
    'geCoordinates': function(distance,location) {
        this.unblock();
        var fut = new Future();
        geocoder.geocode(location, function ( err, data ) {
            if (err) {
                console.log("See on error " + err)
             } else {
                lat = data.results[0].geometry.location.lat 
                lng = data.results[0].geometry.location.lng
            }
                url = 'http://localhost:3005/events?lat='+lat+'&lng='+lng+'&distance='+distance+'&sort=venue&accessToken=1048427405248222|u4dBjiRw-9gdsgml1puWYFGrEvw'
         fut.return(url); // returns the url
        })
    return fut.wait(); // waits until the url is ready
    }
    

    })

    注意:这将同步返回数据。

    【讨论】:

    • 未来没有返回方法?
    • @Villemh 通过使用 'future.return(url)' ,从未来返回 url 但该函数将监听未来的等待方法,直到它准备好
    • 嗯,我收到错误:TypeError: future.return is not a function
    • 对不起我的错误应该是'fut.return(url)'
    • 最后应该有 return fut.wait()
    猜你喜欢
    • 2015-06-03
    • 2013-04-22
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    相关资源
    最近更新 更多