Calling async stuff from method method body

Hi,

Lets say i have case like this.

const myMethod = new ValidatedMethod({
  name: "myMethod",
  async run(params) {
    if (Meteor.isServer) {
      const result = await asyncStuff();
      return result;
    }
  },
});

I want to call some async stuff in the method body. This is done server side only, not in client simulation. Now when client side i call myMethod.call(params, callback) the callback is called with first argument undefined. How do you force the method to wait for server to finish async job and return the result without using Meteor.wrapAsync is it even possible?

When you call a method on the client with ValidatedMethod, it runs on the client first before running on the server.
In your run method, it doesn’t do anything on the client, and because js functions return undefined if you
don’t return anything that means that the promise resolves immedately with undefined and passes that to the callback.

If you want this to be a server only method, you can either mode the definition into server only code, and use Meteor.call,
OR you can set the applyOptions to not use the client side result:

const myMethod = new ValidatedMethod({
  name: "myMethod",
  async run(params) {
    if (Meteor.isServer) {
      const result = await asyncStuff();
      return result;
    }
  },
  applyOptions: {
    returnStubValue: false,
  },
});

Which will still run the client simulation, but should wait for the server result before passing it to the callback

You can call method and use the response it returns, or another way is you can also use Meteor’s webApp to make a route that you query with jQuery async like localhost:3000/myAsyncReq?foo=bar

For some uses cases I prefer the latter, especially for purely frontend stuff because it’s not tangled up in Meteor you just get json out to the client. Methods are also very useful.