简体   繁体   English

在Meteor.method中调用函数返回未定义

[英]Calling a function in Meteor.method returns undefined

I've been trying for the past few days to get a return object from a Meteor method. 在过去的几天里,我一直在尝试从Meteor方法获取返回对象。 Every time I do this I get undefined on the client. 每次执行此操作时,我在客户端上都undefined

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. 任何人都能提供的任何帮助都将是不可思议的。

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. 您的return语句将值从您的匿名函数返回到方法范围, 而不是从服务器方法返回到客户端。 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 . 您可以使用promise ,也可以包装匿名函数调用,并使它与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);
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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