Fabrizio Fortino
Fabrizio Fortino

Reputation: 1616

Meteor: multiple calls to async server method

I need to call 3 times the same server method with different parameters:

  // client code
  var types = ['type1', 'type2', 'type3'];
  for (var i = 0; i < types.length; i++) {
    console.log('client calling', types[i])
    Meteor.call('myMethod', types[i], function (error, result) {
      console.log('client got', types[i])
      Session.set(types[i], result.data);
    });
  }

  // server code
  var Future = Npm.require("fibers/future");

  Meteor.methods({
    myMethod: function (type) {
      var params = {
        type: type
      };

      var future = new Future();
      console.log('server calling', type)
      HTTP.call("GET", Meteor.App.HOST + "/myApi",
        {params: params}, function (error, results) {
          if (error) {
            future.throw(error);
          } else {
            console.log('server got', type)
            future.return(results);
          }
        });

      return future.wait();
    }
  });

The server HTTP call takes up to 10 seconds. Looking at the logs I see:

// client
client calling type1
client calling type2
client calling type3
client got type1
client got type2
client got type3

// server
server calling type1
server got type1
server calling type2
server got type2
server calling type3
server got type3

The client logs are OK. I would expect the same behaviour on the server but it seems that the calls made by one client are executed sequentially. If I start two clients I have the following server logs:

// server
server calling type1
server calling type1
server got type1
server calling type2
server got type1
server calling type2
server got type2
server calling type3
server got type2
server calling type3
server got type3
server got type3

Is this a limitation or my code is not correct?

Upvotes: 0

Views: 369

Answers (1)

user5084201
user5084201

Reputation:

this.unblock() inside a method call will solve this problem, it will not block the meteor method it's good when you do some API calls, sending Emails and don't really have to wait for it to finish

Call inside a method invocation. Allow subsequent method from this client to begin running in a new fiber. http://docs.meteor.com/#/full/method_unblock

Upvotes: 1

Related Questions