Calling a function in Meteor.method returns undefined

岁酱吖の 提交于 2019-12-30 14:41:00

问题


I've been trying for the past few days to get a return object from a Meteor method. Every time I do this I get undefined on the client.

Meteor.methods({
 'CORSTest' : function() {
  let url = "www.theverge.com/2017/4/13/15270854/nasa-enceladus-ocean-hydrothermal-vents-alien-life-conditions-cassini-saturn";
   og(url, function(err, meta){
    if(err){
     console.log(err);
     return "Error";
    } else {
     console.log(meta);
     // Returns the correct Object on the server
     return meta;
    }
  })
 },
})

I've been going crazy over this. Trying all different variables and syntax and I can't seem to get this to work.

Any help anyone can provide would be incredible.


回答1:


This is a very common Meteor question. You are calling an asynchronous function inside your method. Your return statements are returning values from your anonymous function to the method scope, not from the server method to the client. There are several patterns you can follow to get around this. You can use promises or you can wrap your anonymous function call and make it synchronous with Meteor.wrapAsync. For example:

Meteor.methods({
  CORSTest() {
    const url = "www.theverge.com/2017/4/13/15270854/nasa-enceladus-ocean-hydrothermal-vents-alien-life-conditions-cassini-saturn";
    const syncFun = Meteor.wrapAsync(og);
    return syncFun(url);
  }
})


来源:https://stackoverflow.com/questions/43404612/calling-a-function-in-meteor-method-returns-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!