tristantzara
tristantzara

Reputation: 5897

Meteor synchronous method calls

Meteor docs about methods say:

On the server, this function can be run either synchronously or asynchronously. If the callback is omitted, it runs synchronously and the results are returned once the request completes successfully. If the request was not successful, an error is thrown. This is useful when making server-to-server HTTP API calls from within Meteor methods, as the method can succeed or fail based on the results of the synchronous HTTP call. In this case, consider using this.unblock() to allow other methods on the same connection to run in the mean time. On the client, this function must be used asynchronously by passing a callback.

But I find it pretty ambiguous and unobvious, does it just look sync but runs async using fibers, or does it really become sync?

E.g. if I make a server-to-server DDP method call to a meteor app from a meteor app:

const data = anotherMeteorApp.call(...)

Does the code above run sync, blocking the event loop and slowing things down? If it's in a method, would adding this.unblock() before that line of code make it async? If it's not in a method (e.g. if it's in a collection2 hook) would it block?

Upvotes: 1

Views: 555

Answers (1)

Ankur Soni
Ankur Soni

Reputation: 6018

Yes! the code above runs synchronously (if no callback mentioned.), this will slow down things until operation is completed. You can yourself check the impact of adding this.unblock() by sleeping the process inside meteor call at server.

You can use below code to create a simulation of process taking too much time to execute and return from a method defined on server (Meteor.method()).

var breakTime = 20000; // 20 secs
var Future = Npm.require('fibers/future');
var fut = new Future();

var pause = new Promise(function(resolve, reject) {
  setTimeout(() => resolve(1), breakTime);
});
pause.then((1) => {
   fut.return(true);
});
let waitHere = fut.wait();
return true;

Upvotes: 0

Related Questions