![](/img/trans.png)
[英]Meteor: Calling an asynchronous function inside a Meteor.method and returning the result
[英]Calling a function in Meteor.method returns undefined
在过去的几天里,我一直在尝试从Meteor方法获取返回对象。 每次执行此操作时,我在客户端上都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;
}
})
},
})
我为此一直发疯。 尝试所有不同的变量和语法,我似乎无法正常工作。
任何人都能提供的任何帮助都将是不可思议的。
这是一个非常常见的流星问题。 您正在方法内部调用异步函数。 您的return
语句将值从您的匿名函数返回到方法范围, 而不是从服务器方法返回到客户端。 您可以遵循几种模式来解决此问题。 您可以使用promise ,也可以包装匿名函数调用,并使它与Meteor.wrapAsync同步。 例如:
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.