您必须使用HTTP.get 的异步版本并使用Futures 收集结果。
我做了一个简单的例子,使用setTimeouts来模拟HTTP请求,让你理解原理,我建议你从这段代码开始,用你的HTTP get请求替换虚拟的setTimeout。
该示例是一个test 服务器方法,它以多个任务 (n) 作为参数,然后启动 n 个任务,每个任务以索引秒为单位计算其索引的平方。
// we use fibers which is a dependency of Meteor anyway
var Future = Npm.require("fibers/future");
Meteor.methods({
test: function(n) {
// build a range of tasks from 0 to n-1
var range = _.range(n);
// iterate sequentially over the range to launch tasks
var futures = _.map(range, function(index) {
var future = new Future();
console.log("launching task", index);
// simulate an asynchronous HTTP request using a setTimeout
Meteor.setTimeout(function() {
// sometime in the future, return the square of the task index
future.return(index * index);
}, index * 1000);
// accumulate asynchronously parallel tasks
return future;
});
// iterate sequentially over the tasks to resolve them
var results = _.map(futures, function(future, index) {
// waiting until the future has return
var result = future.wait();
console.log("result from task", index, "is", result);
// accumulate results
return result;
});
//
console.log(results);
return results;
}
});
在浏览器控制台中输入 > Meteor.call("test",3,function(error,result){console.log(result);});。这将在 3 秒后输出 [0,1,4]。
在您的服务器控制台中,这将输出:
// immediately :
launching task 0
launching task 1
launching task 2
// after 1 second :
result from task 0 is 0
// after 2 seconds :
result from task 1 is 1
// after 3 seconds :
result from task 2 is 4
[ 0, 1, 4 ]
HTTP.get 异步版本在 Meteor 文档中有详细说明:
http://docs.meteor.com/#http_call
如果您想更好地理解整个 Future 概念,请参阅纤维文档:
https://github.com/laverdet/node-fibers