过去几天我一直在尝试从 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;
}
})
},
})
我为这件事快疯了。尝试所有不同的变量和语法,我似乎无法让它工作。
任何人都能提供的任何帮助都是令人难以置信的。
最佳答案
这是一个非常常见的 Meteor 问题。您正在方法内调用异步函数。您的 return
语句将值从匿名函数返回到方法作用域,而不是从服务器方法返回到客户端。您可以遵循多种模式来解决这个问题。您可以使用promises或者您可以包装匿名函数调用并使其与 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);
}
})
关于javascript - 在 Meteor.method 中调用函数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43404612/