Can we use async/await to define meteor method?


#1

for example

Meteor.methods({
  async 'myMethod'(arg1) {
    ...
    const result = await otherAsyncApi();
    ...
    return finalResult
  }
})

is this correct? what’s the evidence behind it? will using this pattern cause any problem instead of using Meteor.wrapAsync?


#2

Yes (although you don’t actually need the quotes around a “simple” name like myMethod).

Errm - that’s how it’s designed to work - the Promise will be resolved before the data is sent over the wire. I should just add that I found an issue with in-server calls to async methods when I was testing this a few months back. That may or may not be fixed now - I haven’t retested that specific usage.

Meteor.wrapAsync is used to wrap asynchronous functions with a signature of (error, result) into a fiber/future. Using async/await lets you handle Promises in sync-style. If those Promises have not been defined correctly then you’ll get problems - but you’d get problems with wrapAsync if you’re trying to wrap a function with a different signature.


#3

Wow, thanks. That means now we have a strong weapon to use async npm packages in meteor server than before. A little curious about why few people mentioned this. Thanks.