问题
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