问题描述
我遇到了一些我不明白流星。我有这种方法,这需要一个查询,它发送到亚马逊,然后在该函数的回调我尝试返回结果。
I am running into something I don't understand with Meteor. I have this method, which takes a query, sends it to amazon, and then in the callback of that function I try to return the results.
Meteor.methods({
'search': function(query) {
var bookInfo;
if (Meteor.isServer) {
amazon.execute('ItemSearch', {
'SearchIndex': 'Books',
'Keywords': query,
'ResponseGroup': 'ItemAttributes'
}, function(results) {
bookInfo = results;
console.log(bookInfo);
return bookInfo;
});
}
}
});
但是,当我把下列控制台在我的浏览器(Chrome):
But when I put the following into the console in my browser (chrome):
Meteor.call('search', 'harry potter', function(error, response) {
console.log('response:', response);
});
我得到这样的:
undefined
response: undefined VM13464:3
我想我明白,第一个不确定来自于方法不返回客户端上的任何东西,但回调似乎并没有在所有的工作。
I think I understand that the first undefined comes from the method not returning anything on the client, but the callback doesn't seem to work at all.
该amazon.execute(...)绝对是返回的东西,为的console.log权的回报上面并登录我要找的信息。
The amazon.execute(...) is definitely returning something, as the console.log right above the return does log the info I'm looking for.
任何想法什么错,我该如何解决这个问题?
Any ideas what's going wrong and how I can fix it?
推荐答案
您需要使用未来,以实现自己的目标。
You need to use Future to achieve your goal.
如何使用未来,因为流星0.6?
How to use future since Meteor 0.6?
Meteor.startup(function () {
Future = Npm.require('fibers/future');
// use Future here
}
您使用的方法改写未来:
Your method rewritten with Future:
Meteor.methods({
'search': function(query) {
var future = new Future();
amazon.execute('ItemSearch', {
'SearchIndex': 'Books',
'Keywords': query,
'ResponseGroup': 'ItemAttributes'
}, function(results) {
console.log(results);
future["return"](results)
});
return future.wait();
}
});
现在它应该工作。
Meteor.call('search', 'harry potter', function(error, response) {
if(error){
console.log('ERROR :', error);
}else{
console.log('response:', response);
}
});
如果您想了解更多关于未来库,我建议看
If you want to learn more about Future library I recommend watching screencast
这篇关于从回调返回值的范围内Meteor.method的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!