假设我有代码从多个集合中获取数据,如下所示。
//code running on server.
var a = collectionA.findOne({...});
var b = collectionB.findOne({...});
var c = collectionC.findOne({...});
var d = collectionD.findOne({...});
如果我没错,上面的代码将以串行方式运行。因此,等待获取集合的时间将会增加,并且响应时间将延迟。
有没有办法以并行方式运行上面的代码,最好是promise模式?
答案 0 :(得分:0)
Meteor不使用promise或async,它使用Fibers。 您可以直接使用它或通过方法使用它。
使用方法可能如下所示:
了Serverside:
function fetchAFromDB(arg,cb){ //function needs a callbac
var a = collectionA.findOne(arg);
if (!a) {
cb(new Meteor.Error("a-not-found", "Can't find a"));
else
cb(null,a) //first argmument is always an error
}
Meteor.methods({
fetchA: function (arg) {
var fetchAAsync = Meteor.wrapAsync(fetchAFromDB); //wrap function as async
var result = fetchAAscync(arg); //execute function
return result; //return value
}
}
//call method on the server
//async
Meteor.call('fetchA', {_id:'foo'}, function (error, result) { ... } );
//blocking
var result = Meteor.call('fetchA', {_id:'foo'});
将其称为客户端:
Meteor.call('fetchA', {_id:'foo'}, function (error, result) { ... } );
另一种方法是直接使用光纤(Documentation for fibers):
对于您的用例,它可能看起来像这样:
了Serverside:
function doSomethingWith(a){...} //does something with a
var Fiber = Npm.require('fibers');
var async = Fiber(function() {
var a = collectionA.findOne({...});
return doSomethingWith(a);
});
//calls you async function
async.run();