Meteor js parallel db fetch.

Let's say I have some code that retrieves data from multiple collections as follows.

//code running on server.
var a = collectionA.findOne({...});
var b = collectionB.findOne({...});
var c = collectionC.findOne({...});
var d = collectionD.findOne({...});

      

If I am not mistaken the code will work serially. Thus, the waiting time for retrieving the collection will add up and the response time will be delayed.

Is there a way to run over the code in parallel, preferably to promise a template?

+3


source to share


1 answer


Meteor doesn't use promise or asynchronous, it uses Fibers. You can use it directly or using methods.

With a method, it might look like this:

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'});

      

Call it clientide:



Meteor.call('fetchA', {_id:'foo'}, function (error, result) { ... } );

      

Another way would be to use fiber directly ( Documentation for fibers ):

It might look like this for your use case:

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();

      

0


source







All Articles